【发布时间】:2019-12-28 22:27:18
【问题描述】:
我收到一个 TypeError,说在集合上运行 while 循环时,'int' 类型的对象没有 len()。
import random
l = random.sample(range(100), 20)
s = set()
print(s)
print(len(s))
while len(s) < 4:
s = random.choice(l)
我从打印语句(set() 和 0)中得到了正确的输出,但是当它到达 while 循环时出现了前面提到的 TypeError。
【问题讨论】:
-
第一次迭代后
s变成int和s = random.choice(l)。 -
你可能想要
s.add(random.choice(l)) -
s = set(random.sample(l, 4))。sample已经避免了重复。