Choose an index from a list

1

I have a list:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

I would like to choose a value between indexes 6 and 14 from this list, but do this 5 times and store those values in another list. How do I?

If it were of any index, it would be:

random.choose(l)

But that's not what I want. Can you help me please?

    
asked by anonymous 16.07.2016 / 12:48

2 answers

1

Now I can not test but I believe you can do it:

index1 = 6
index2 = 14
vals = []

for i in range(0, 5):
    # l[index1:index2] = lista dos valores entre index1 e index2
    vals.append(random.choice(l[index1:index2])) # aqui armazena os valores

Do not store repeats instead of for loop do:

while len(vals) < 5:
    randVal = random.choice(l[index1:index2])
    if randVal not in vals:
        vals.append(randVal)

Note that this way you have to ensure that there are more than 5 (or 5) values between index1 and index2, otherwise it will cycle infinitely.

    
16.07.2016 / 12:58
0

Just pass a subset of the list to random.choice:

random.choice(l[6:14])
    
17.07.2016 / 19:33