Choosing an index from a list

Asked

Viewed 74 times

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 the indexes 6 and 14 of this list, but do this 5 times and store these values in another list. How do I?

If it were any index, it would be:

random.choose(l)

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

  • in fact l is a list of lists, something like: l = [lista1, lista2, lista3, lista4, ..., lista15] and lista1 = [1, 2, 3], lista2 = [4, 5, 6], etc

2 answers

1


Now I can’t test but I think you can do:

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

Not to store repeated instead of cycle for do:

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

Be careful that in this way you have to ensure that there are more than 5 (or 5) values between index1 and index2, otherwise it goes into infinite cycle.

  • jewelry friend @Miguel, I will test! where I am now I can only communicate here haha

  • Is there any way I can choose instead of an index value, choose my own index? I did it here and it worked, but it doesn’t go through the index, but by the value of each item in each index.

0

Just pass a subset of the list to Random.Choice:

random.choice(l[6:14])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.