Python - for loop: TypeError: 'int' object is not iterable

Python - for loop: TypeError: 'int' object is not iterable

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

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 的每个元素都是一对,您想循环遍历它,将每对解包为 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.