python - 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 个元素,我希望将其从列表中删除。
解决方案
从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: []
推荐阅读
- javascript - 我可以返回一个函数构造函数并在其他函数中使用吗
- swift - 如果我转到另一个视图控制器并使用 segue 返回到同一个视图控制器,snapshotListener 是否会重新读取所有文档?
- android - kotlinx.serialization :如何解析为与 JSON 键的确切名称不同的变量名称
- python - 熊猫分位数行为不端...在百分位数范围内变小?
- c# - 数据未插入 Cosmos C#
- php - 选择多个表 PHP
- linq - 使用 Mapster 调整导航属性
- python - 无法使用 xpath 获取表格行
- python - 在熊猫数据框中创建索引第一行
- c++ - 在 C++ 中创建具有当前日期和时间的文件