【问题标题】:How to know which list python chooses with random.choice如何知道 python 使用 random.choice 选择哪个列表
【发布时间】:2012-11-07 20:55:25
【问题描述】:

我想知道 python 使用random.choice 选择哪个列表,以便我可以使用if 语句来获得不同的结果。

thelists = [L1, L2, L3, L4, L5, L6]
theplayers = random.choice(thelists)

我想知道选择 theplayers 的变量是哪个列表,L1,L2...。

【问题讨论】:

  • 或者,index, lst = random.choice(list(enumerate(thelists))) 或使用哈希而不是列表并执行 list_name, lst = random.choice(thehashoflists.items())

标签: python list random choice


【解决方案1】:

为什么不改用random.randint,这样以后就不用list.index来查找列表了:

from random import randint

# your list of lists
l = [[1,2,3],[4,5,6],[7,8,9]]
# choose a valid *index* into l, at random
index = randint(0,len(l) - 1)
# use the randomly chosen index to get a reference to the list
choice = l[index]

# write your conditionals which handle different choices
if index == 1:
    print 'first list'
elif index == 2:
    print 'second list'
...

这将比每次做出选择时使用random.choice 然后list.index 更有效。

【讨论】:

  • 这个或random.choice(enumerate(thelists)) 似乎是最明智的选择。
  • @hayden: 必须是list(enumerate(thelists)),我想 -- random.choice 需要知道长度。
  • @DSM 好点,很难从可能无限的生成器中统一选择!
【解决方案2】:

很简单:

 res = random.choice(my_list)

【讨论】:

  • @user1807371:“res”/“theplayers”将保存所选列表。你还在纠结别的事情吗?
【解决方案3】:

看看documentation

random.choice(seq)

从非空序列中返回一个随机元素 seq。如果seq 为空,则引发IndexError

这里,seq 是您的列表。

您可以通过以下方式获取所选元素的索引:

thelists.index(theplayers)

【讨论】:

  • .index() 不一定有效。如果有两个相等的列表,.index() 只会告诉你第一个在哪里。
  • 不会有相同的列表^所以这会正常工作:p
  • 除了@DSM所说的之外,保留索引也更简单(也更有效),而不是像所有其他答案中提到的那样丢弃并再次搜索它。这真的不应该是您接受(并实施)的答案。
猜你喜欢
  • 2011-09-01
  • 2023-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 2013-09-08
相关资源
最近更新 更多