简体   繁体   中英

Making a list of lists in a For Loop

How do you make a list of lists within a for loop?

Here is what I have coded right now:

    a = 0
    xy=[[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]],[[],[]]]
    for liness in range(len(NNCatelogue)):
        a=0
        for iii in range(len(NNCatelogue[liness])):

            while a < len(catid):

                if catid[a]==NNCatelogue[liness][iii]:

                    xyiii = (catid[a], a)
                    xy.append(xyiii)   
                a += 1

The output that I get is a lengthy list of pairs, as expected. It looks somewhat like the following:

     [...,('C-18-1262', 30908),
     ('C-18-1264', 30910),
     ('C-18-1265', 30911),
     ('C-18-1267', 30913),
     ('C-18-1250', 30896),
     ('C-18-1254', 30900),...]

I would like to turn this list of pairs into a list of lists of pairs though. There are 1268 iterations, and the length of each list should be 12. (So 1268 lists with 12 elements in each of them). Any ideas for how to approach this when in a loop?

Something like this, perhaps. Note that I am using iteration over the lists directly to save a lot of unnecessary indexing.

xy = []
for line in NNCatelogue:
    l = []
    for c in line:
        for a, ca in enumerate(catid):
            if ca == c:
                l.append((ca, a))
    xy.append(l)

If you're using the inner loop just to search for the category index, as I suspect you are, a dictionary may be a useful addition to avoid the inner loop.

I have a few friendly suggestions right off the bat:

  1. First of all, the a=0 at the very beginning is redundant. You do the same thing twice with the a=0 inside of the first for loop.

  2. Second, why are you declaring a huge framework of list elements for xy at the top? You can always append() what you need as you go along.

  3. Finally, your while loop is just a simple for loop:

     for n in range(len(catid)): 

You can make a list of lists using list expansions like so:

list_of_lists = [[j for j in range(0, 3)] for _ in range(0, 3)]

Which outputs a 3x3 list:

[ [0, 1, 2], 
  [0, 1, 2], 
  [0, 1, 2]
]

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