【问题标题】:Why am I getting a "TypeError: object of type 'int' has no len()" on a set?为什么我在集合上收到“TypeError:'int' 类型的对象没有 len()”?
【发布时间】: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 变成ints = random.choice(l)
  • 你可能想要s.add(random.choice(l))
  • s = set(random.sample(l, 4))sample 已经避免了重复。

标签: python int set typeerror


【解决方案1】:

这是因为您的 while 循环将值切换为 s = random.choice(l) 处的整数。见:

import random
l = random.sample(range(100), 20)

s = set()
print(s) 
print(len(s))
while len(s) < 4:
    s = random.choice(l)
    print(s)

返回:

set()
0
50

然后给你类型错误。所以你得到了错误,因为 s 最初是一个集合,然后它被切换到 int 并返回到 while 循环并且没有 len

【讨论】:

    【解决方案2】:

    您需要将结果添加到set,否则您只是将set重新分配给random.choice的结果,即int

    while len(s) < 4:
        s.add(random.choice(l))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多