简体   繁体   English

TypeError: 'int' 对象不可迭代 - 但它是一个列表

[英]TypeError: 'int' object is not iterable - but is a list

I have a list of lists that I want to iterate over for reasons later in the project.我有一个列表列表,由于项目后期的原因,我想对其进行迭代。 However, when I try to iterate over each list in the normal, pythonic way, I get an the error TypeError: 'int' object is not iterable .但是,当我尝试以正常的 Pythonic 方式迭代每个列表时,我收到错误TypeError: 'int' object is not iterable So, to test how the code was working I wrote所以,为了测试代码是如何工作的,我写了

for i in self.features:
  print(i)
  print("Test1")

for i in len(self.features):
  print(i)
  print("Test2")

The program is successfully able to execute all the items in the Test1 loop, and none in the second.该程序能够成功执行 Test1 循环中的所有项目,并且在第二个循环中没有执行。 For the first test the output is:对于第一次测试,输出为:

Test1
2      169.091522
3      171.016678
4      170.381485
5      170.361954
6      170.322845
 ....
245    149.510544
246    145.642090
247    155.898438
248    154.886688
249    154.966034
Name: Adj Close, Length: 248, dtype: float64

So, features seems to be a list of lists, just like I had wanted, but it appears to not want to allow me to do the things you can typically do with a list.所以,特性似乎是一个列表列表,就像我想要的那样,但它似乎不想让我做你通常可以用列表做的事情。

To see the code in action, you can run it here https://repl.it/@JacksonEnnis/KNNFinalProduct要查看正在运行的代码,您可以在此处运行它https://repl.it/@JacksonEnnis/KNNFinalProduct

len() returns the length of a list as an int . len()int返回列表的长度。 Python will be interpreting your code as: Python 会将您的代码解释为:

for i in 5:
  print(i)
  print("Test2")

It will fail when interpreting the for statement and will never enter the loop.解释for语句时会失败,永远不会进入循环。


To correctly iterate over the list your first snippet is correct.要正确迭代列表,您的第一个片段是正确的。

for i in self.features:
  print(i)
  print("Test1")

If you wanted to iterate through a range of numbers up to the size of your list, you should use range() .如果您想遍历一系列数字,直到您的列表大小,您应该使用range()

for i in range(1, len(self.features) + 1):
  print(i)
  print("Test2")

As suggested by @PeterWood you could also use enumerate() .正如@PeterWood 所建议的,您也可以使用enumerate()

for i, _ in enumerate(self.features, 1):
  print(i)
  print("Test2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM