首页 > 解决方案 > python中for循环内列表元素的随机选择选择

问题描述

num=[1,2,3,4,5,6]
for c in num:
    print("selected :",random.choice(c))

TypeError: object of type 'int' has no len()

这段代码有什么问题?我希望使用 for 循环随机选择列表中的单个元素。

期望的输出:

selected :3 

或者

selected :6 

我正在循环一个列表,因为如果选择了 1 个元素,我希望将其从列表中删除。

标签: pythonloops

解决方案


random.choice文档中,它接受一个序列

随机选择(序列)

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

因此,传入 的每个元素是错误的num,即 a int,这将导致 a TypeError

  File "/.../python3.8/random.py", line 288, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'int' has no len()

您需要传入num自身,然后它从中返回一个随机元素。

>>> num = [1,2,3,4,5,6]
>>> print("selected :", random.choice(num))
selected : 4
>>> print("selected :", random.choice(num))
selected : 5
>>> print("selected :", random.choice(num))
selected : 2

循环在for这里没有多大意义(因此评论中的问题),因为您不需要将每个元素传递给random.choice.

你之前这么说:

我正在循环一个列表,因为如果选择了 1 个元素,我希望它在列表中被删除。

我不确定您的实际目的是什么,但也许while循环更合适。例如,您可以继续从列表中选择随机元素并在列表不为空时将其从列表中删除。

>>> num = [1, 2, 3, 4, 5, 6]
>>> while len(num) > 0:
...   n = random.choice(num)
...   print("selected : ", n)
...   num.remove(n)
...   print("num is now: ", num)
... 
selected :  3
num is now:  [1, 2, 4, 5, 6]
selected :  5
num is now:  [1, 2, 4, 6]
selected :  4
num is now:  [1, 2, 6]
selected :  1
num is now:  [2, 6]
selected :  6
num is now:  [2]
selected :  2
num is now:  []


推荐阅读