在python中的列表中构建列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18980396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:29:59  来源:igfitidea点击:

Building a list inside a list in python

pythonlist

提问by Pensu

I have been trying to add some data in a python list. I am actually going to store the data as a list inside a list. Now, the data is not coming index-wise.

我一直在尝试在 python 列表中添加一些数据。我实际上将数据存储为列表中的列表。现在,数据不是按索引来的。

To explain that lets say I have a list of lists 'a'. Now I have data for a[2]before a[1]. And both a[1]and a[2]are lists themselves. Now, obviously I can't assign anything to a[2]before assigning a[1]. And I don't know how much lists would be there. I mean, this is supposed to be dynamic.

为了解释这一点,可以说我有一个列表“a”。现在我有a[2]之前的数据a[1]。并且a[1]a[2]都是列表本身。现在,显然我不能a[2]在分配之前分配任何东西a[1]。而且我不知道会有多少列表。我的意思是,这应该是动态的。

Any solution to this, so that I can successfully build the list?

对此有什么解决方案,以便我可以成功构建列表?

采纳答案by Martijn Pieters

You could append empty lists until you have enough to access the index you have data for:

您可以附加空列表,直到您有足够的资源访问您拥有数据的索引:

while len(outerlist) <= idx:
    outerlist.append([])

However, you may want to use a dictionary instead, letting you implement a sparseobject instead. A collections.defaultdict()objectis especially useful here:

但是,您可能希望改用字典,让您实现稀疏对象。一个collections.defaultdict()对象是在这里尤其有用:

from collections import defaultdict

data = defaultdict(list)

data[2].append(3)
data[5].append(42)

datanow has keys 2and 5, each a list with one element. No entries for 0, 1, 3, or 4exist yet.

data现在有键25,每个都是一个包含一个元素的列表。没有条目013,或4存在呢。

回答by jabaldonedo

You can do it, there is no problem appending an element.

你可以做到,追加元素没有问题。

>>> a = [[1,2,3], [10,20,30], [100,200,300]]
>>> a[2].append(400)
 [[1, 2, 3], [10, 20, 30], [100, 200, 300, 400]]
>>> a[1].append(40)
 [[1, 2, 3], [10, 20, 30, 40], [100, 200, 300, 400]]

回答by Hellseher

I had the same problem, to fill empty list with definite amount of lists. Here is my way out I made a "board" 6x6 filled with O, just for instant:

我有同样的问题,用一定数量的列表填充空列表。这是我的出路,我制作了一个充满 O 的“板”6x6,只是为了即时:

board = []    
for i in range(6): # create a list with nested lists
    board.append([])
    for n in range(6):
        board[i].append("O") # fills nested lists with data

Result:

结果:

[['O', 'O', 'O', 'O', 'O', 'O'],
 ['O', 'O', 'O', 'O', 'O', 'O'],
 ['O', 'O', 'O', 'O', 'O', 'O'], 
 ['O', 'O', 'O', 'O', 'O', 'O'],
 ['O', 'O', 'O', 'O', 'O', 'O'],
 ['O', 'O', 'O', 'O', 'O', 'O']]

回答by Viswesn

We can use the first item in the list as an index and then make use of it for adding the right value to it at runtime using the list.

我们可以使用列表中的第一项作为索引,然后利用它在运行时使用列表向其添加正确的值。

def unclean_(index, val, unclean=None):
   is_added = False
   if unclean is None:
       unclean = []
   length = len(unclean)
   if length == 0:
       unclean.append([index, val])
   else:
       for x in range(length):
            if unclean[x][0] == index:
                unclean[x].append(val)
                is_added = True
       if not is_added:
            unclean.append([index, val])

def terminate_even(x):
    if x % 2 == 0:
        raise Exception("Its even number")

def terminate_odd(x):
    if x % 2 != 0:
        raise Exception("Its odd number")

def fun():
    unclean = []
    for x in range(10):
       try:
            terminate_even(x)
       except:
            unclean_("terminate_even", x, unclean)

    for x in range(10):
       try:
            terminate_odd(x)
       except:
            unclean_("terminate_odd", x, unclean)

    for y in unclean:
        print y

 def main():
    fun()

 if __name__ == "__main__":
    main()

 Output:
 -------
     ['terminate_even', 0, 2, 4, 6, 8]
     ['terminate_odd', 1, 3, 5, 7, 9]

回答by Chandan Venkatesh

I think this solution solves your problem.

我认为这个解决方案可以解决您的问题。

Create the secondary list(inside_list) local to the for loop

创建for循环本地的辅助列表(inside_list)

    outside_list=[]
    for i in range(0,5):
        inside_list=[]
        inside_list.append(i)
        inside_list.append(i+1)
        outside_list.append(inside_list)

       #you can access any inside_list from the outside_list and append     
        outside_list[1].append(100)
        print(outside_list)

Output:

输出:

[[0, 1], [1, 2, 100], [2, 3], [3, 4], [4, 5]]
[[0, 1], [1, 2, 100], [2, 3], [3, 4], [4, 5]]