繁体   English   中英

列表中的随机元素

[英]random element from a list

python中有没有一种方法可以从列表中选择一个随机元素而不考虑当前元素?

换句话说,我想这样做

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

例如,在迭代0时,我不想拥有元素1 ;在迭代1时,我不想拥有元素2

您可以基于切片创建一个新列表:

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

或者简单地绘制一个随机索引,直到您绘制的索引不等于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

如果需要性能,也可以在0len(L)-1之间绘制一个索引,如果等于或大于i则将其递增1。 这样,您就无需重新绘制,索引i被排除在外:

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

您只需选择一个除当前索引以外的随机元素,然后就可以尝试

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