【问题标题】:Python - for loop: TypeError: 'int' object is not iterablePython - for循环:TypeError:'int'对象不可迭代
【发布时间】:2022-01-01 11:51:08
【问题描述】:

我正在尝试使用下面的代码来检查是否允许某人乘坐过山车。第一部分是创建一个二维列表,第二部分是检查。

heights = [165, 154, 156, 143, 168, 170, 163, 153, 167]
ages = [18, 16, 11, 34, 25, 9, 32, 45, 23]

heights_and_ages = list(zip(heights, ages))
heights_and_ages = [list(info) for info in heights_and_ages]

can_ride_coaster = []
for info in heights_and_ages:
  for height, age in info:
    if height > 161 and age > 12:
      can_ride_coaster.append(info)

我在第 19 行得到错误

for height, age in info:

错误是:

line 19, in <module>
    for height, age in info:

TypeError: cannot unpack non-iterable int object

我认为是因为我使用了两个变量bcs,如果我使用一个就可以了,但是在网上搜索后似乎没有问题。我该如何解决这个问题?

【问题讨论】:

  • 尝试使用 heights_and_ages = [[list(info)] 获取 heights_and_ages 中的信息]

标签: python python-3.x for-loop typeerror


【解决方案1】:

这里似乎不需要嵌套循环。 heights_and_ages 的每个元素都是一对,您希望循环遍历它,将每一对解包为 heightage

for height, age in heights_and_ages:
    if height > 161 and age > 12:
        can_ride_coaster.append((height,age))

这有助于列表理解:

can_ride_coaster = [(h,a) for (h,a) in heights_and_ages if h > 161 and a > 12]

为什么你的代码会出错?

假设info[165, 18]。当你写

for height, age in info:

您是在说“循环通过 info 并将每个元素解压缩到 height, age”。

在该循环的第一次迭代中,元素为 165,您尝试将单个 int 值解压缩为多个变量。这就是你得到int object is not iterable的原因。

【讨论】:

  • 谢谢,没意识到。但是,如果您不介意我问,为什么原始代码会产生这样的错误?仅在 2 天前开始学习编码,因此将不胜感激?
  • 我在回答中添加了更多解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2013-10-31
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多