【问题标题】:random element from a list列表中的随机元素
【发布时间】:2017-11-10 02:20:55
【问题描述】:

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

【问题讨论】:

    标签: python python-2.7 list random


    【解决方案1】:

    您可以根据切片创建一个新列表:

    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
    

    【讨论】:

      【解决方案2】:

      所有你必须选择当前索引以外的随机元素,然后你可以试试这个

      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
      

      【讨论】:

        猜你喜欢
        • 2012-02-07
        • 2021-12-30
        • 2014-06-12
        • 1970-01-01
        • 2015-09-22
        • 2015-05-03
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多