简体   繁体   English

列表中的随机元素

[英]random element from a list

Is there a way in python to select a random element form a list without considering a current element? python中有没有一种方法可以从列表中选择一个随机元素而不考虑当前元素?

In other word, I want to do this 换句话说,我想这样做

L=[1,2,3,4,5,6,7,8,9,10]
i=0
while(i<len(L):
  random.choice(L-L[i])
  i+=1

For example, at iteration 0 I do not want to have the element 1 and at iteration 1 I do not want to have the element 2 . 例如,在迭代0时,我不想拥有元素1 ;在迭代1时,我不想拥有元素2

You could create a new list based on slicing: 您可以基于切片创建一个新列表:

L = [1,2,3,4,5,6,7,8,9,10]
i = 0
while i < len(L):
    random.choice(L[:i] + L[i+1:])  # L without the i-th element
    i += 1

Or simply draw a random index until you draw an index that isn't equal to i : 或者简单地绘制一个随机索引,直到您绘制的索引不等于i为止:

while i < len(L):
    while True:
        num = random.randrange(0, len(L))  # draw an index
        if num != i:                       # stop drawing if it's not the current index
            break
    random_choice = L[num]
    i += 1

If you need performance you could also just draw an index between 0 and len(L)-1 and increment it by 1 if it's equal or higher than i . 如果需要性能,也可以在0len(L)-1之间绘制一个索引,如果等于或大于i则将其递增1。 That way you don't need to re-draw and index i is excluded: 这样,您就无需重新绘制,索引i被排除在外:

while i < len(L):
    idx = random.randrange(0, len(L) - 1)
    if idx >= i:
        idx += 1                     
    random_choice = L[idx]
    i += 1

All you have to pick a random element other than the current index , then you can try this 您只需选择一个除当前索引以外的随机元素,然后就可以尝试

l=[i for i in range(1,11)]
from random import random
for i in l:
    while 1:        
        tmp= int(random() * 10) 
        if tmp!=i:      
            print tmp
            break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM