[英]How do I iterate through lists with nested lists in Python / why doesn't my code work?
Can someone explain why Python won't let me use i in this manner?有人可以解释为什么 Python 不允许我以这种方式使用 i 吗?
unit1 = [["cats allowed", True], ["bedrooms", 0], ["Balcony", False]]
userPref = []
for i in unit1:
userPref = userPref.append(unit1[i][1])
print(unit1[i][1])
I get this error message:我收到此错误消息:
TypeError: list indices must be integers or slices, not list
If I want to iterate through the second item in each nested list, how would I go about doing that?如果我想遍历每个嵌套列表中的第二项,我将如何 go 这样做?
(FYI: the for loop in nested in an if statement. I omitted that for simplicity.) (仅供参考:for 循环嵌套在 if 语句中。为简单起见,我省略了它。)
Some options you have to iterate over a list:您必须遍历列表的一些选项:
1) 1)
for item in unit1:
userPref.append(item[1])
print(item[1])
which item[1]
is the second parameter of nested list which
item[1]
是嵌套列表的第二个参数
2) 2)
for i in range(len(unit1)):
userPref.append(unit1[i][1])
print(unit1[i][1])
or if you need item
and index
together:或者如果您需要一起使用
item
和index
:
for i,item in enumerate(unit1):
userPref.append(item[1])
print(item[1])
for i in unit1:
When you iterate over a list in this way, i
becomes each value in the list, not the list index .当您以这种方式遍历列表时,
i
成为列表中的每个值,而不是列表索引。
So on the first iteration, i
is the sub-list ["cats allowed", True]
.所以在第一次迭代中,
i
是子列表["cats allowed", True]
。
If you want to iterate over the indexes of a list, use range()
:如果要遍历列表的索引,请使用
range()
:
for i in range(len(unit1)):
Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
Python 的 for 语句按照它们在序列中出现的顺序迭代任何序列(列表或字符串)的项目。
You can found that differ in python official tutorial , the iteration will traverse all the value in the sequence rather index of that, which is quite different from other languages.你可以在python官方教程中发现不同的是,迭代会遍历序列中的所有值而不是那个索引,这与其他语言有很大的不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.