简体   繁体   中英

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?

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?

(FYI: the for loop in nested in an if statement. I omitted that for simplicity.)

Some options you have to iterate over a list:

1)

for item in unit1:
   userPref.append(item[1])
   print(item[1])

which item[1] is the second parameter of nested list

2)

for i in range(len(unit1)):
    userPref.append(unit1[i][1])
    print(unit1[i][1])

or if you need item and index together:

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 .

So on the first iteration, i is the sub-list ["cats allowed", True] .

If you want to iterate over the indexes of a list, use 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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