【问题标题】:"TypeError: 'int' object is not iterable" on for loop, but not in list comprehension\"TypeError: \'int\' object is not iterable\" on for loop, but not in list comprehension
【发布时间】:2023-02-17 23:33:55
【问题描述】:

我正在编写代码来检查嵌套列表中每个列表的相同索引是否相同。我试着把它写成一个 for 循环,但我得到了“TypeError: 'int' object is not iterable”。然后我尝试进行列表理解,但没有得到 TypeError。我是编程新手,所以我真的不知道这两个表达式是否应该做同样的事情。有人可以帮助我了解它们之间的区别以及为什么我在 for 循环中遇到 TypeError 吗? 它应该验证数独,因此嵌套列表的长度应该与每个子列表的长度相同。

对于循环:

for l in nlist:
    if len(set(l[0])) != len(nlist):
        return False

列表理解:

validate_nlist = len(set(l[0] for l in nlist)) == len(nlist)

【问题讨论】:

  • 显示一些测试列表将极大地帮助更好地理解问题。
  • 你的父母不一样。
  • 你在第二个 sn-p 中写的根本不是列表推导式,而且你也不想在这里使用列表推导式。 for 循环的等效项是 any() 调用中的生成器,例如return not any(len(set(l[0])) != len(nlist) for l in nlist)

标签: python for-loop nested


【解决方案1】:

为此使用any

if any(len(set(l[0])) != len(nlist) for l in nlist):
    return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2020-05-07
    • 2019-04-12
    • 2016-02-18
    • 2022-11-02
    • 2018-06-29
    • 2020-11-07
    • 2016-01-09
    相关资源
    最近更新 更多