简体   繁体   English

在For循环中列出列表

[英]Making a list of lists in a For Loop

How do you make a list of lists within a for loop? 如何在for循环中列出列表?

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). 有1268次迭代,每个列表的长度应为12。(因此1268个列表中每个都有12个元素)。 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. 首先,一开始的a = 0是多余的。 You do the same thing twice with the a=0 inside of the first for loop. 您在第一个for循环中使用a = 0进行了两次相同的操作。

  2. Second, why are you declaring a huge framework of list elements for xy at the top? 其次,为什么要在顶部声明一个庞大的xy列表元素框架? You can always append() what you need as you go along. 您随时可以随需添加append()。

  3. Finally, your while loop is just a simple for loop: 最后,while循环只是一个简单的for循环:

     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: 输出3x3列表:

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

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

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