简体   繁体   中英

defining a list of lists and iterating over it

how can I iterate over a list of lists like this:

kinds = [[1],[2],[3]]
1 = [[x],[y],[z]]
2 = [[k],[l],[m]]
3 = [[z],[y],[w]]
for i in kinds:
    for j in in each element of kinds:
        #do this 

You cannot name a variable with just a single number.But here is a solution for your problem;Take this for example:

var1 = [1,2,4]
var2 = [6,2,1]
var3 = ['NN','VBG','JJR']
kinds = [var1,var2,var3]
for list in kinds:
    for items in list:
         print (items)

output:

1
2
4
6
2
1
NN
VBG
JJR

For a simple nested list, this will do:

kinds = [[1],[2],[3]]
for i in kinds:  # i is a list, so iterate it!
    for j in i:  # assumes kinds is list of lists (iterable of iterables)
        # do stuff

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