简体   繁体   English

将新项目追加到列表中的列表中

[英]Append a new item to a list within a list

I'm trying to append a new float element to a list within another list, for example: 我试图将新的float元素追加到另一个列表中的列表中,例如:

list = [[]]*2
list[1].append(2.5)

And I get the following: 我得到以下信息:

print list
[[2.5], [2.5]]

When I'd like to get: 当我想得到:

[[], [2.5]]

How can I do this? 我怎样才能做到这一点?

Thanks in advance. 提前致谢。

lst = [[] for _ in xrange(2)] (or just [[], []] ). lst = [[] for _ in xrange(2)] (或仅[[], []] )。 Don't use multiplication with mutable objects — you get the same one X times, not X different ones. 不要对易变的对象使用乘法-您得到的X相同,而不是X的不同。

list_list = [[] for Null in range(2)]

dont call it list , that will prevent you from calling the built-in function list() . 不要调用它list ,这将阻止您调用内置函数list()

The reason that your problem happens is that Python creates one list then repeats it twice. 发生问题的原因是Python创建一个列表,然后重复两次。 So, whether you append to it by accessing it either with list_list[0] or with list_list[1] , you're doing the same thing so your changes will appear at both indexes. 因此,无论您是通过使用list_list[0]还是使用list_list[1]访问它来附加它,您都在做相同的事情,因此您的更改将同时出现在两个索引上。

You can do in simplest way.... 您可以用最简单的方式做...。

>>> list = [[]]*2
>>> list[1] = [2.5]
>>> list
[[], [2.5]]
list = [[]]
list.append([2.5])

or 要么

list = [[],[]]
list[1].append(2.5)

[] is a list constructor, and in [[]] a list and a sublist is constructed. []是一个列表构造函数,并且在[[]]中构造了一个列表和一个子列表。 The *2 duplicates the reference to the inner list, but no new list is constructed: *2复制对内部列表的引用,但不构造新列表:

>>> list[0] is list[1]
... True
>>> list[0] is []
... False

The solution is to have 2 inner lists, list = [[], []] 解决方案是有2个内部列表, list = [[], []]

As per @Cat Plus Plus dont use multiplication.I tried without it.with same your code. 按照@Cat Plus Plus不要使用乘法。我尝试了没有乘法。使用相同的代码。

>> list = [[],[]]
>> list[1].append(2.5)
>> list
>> [[],[2.5]]

you should write something like this: 您应该这样写:

>>> l = [[] for _ in xrange(2)]
>>> l[1].append(2.5)
>>> l
[[], [2.5]]

Your outter list contains another list and multiplying the outter list will have the resulting list's items all have the same pointer to the inner list. 您的外部列表包含另一个列表,乘以外部列表将使结果列表的所有项都具有指向内部列表的相同指针。 You can create a multidimensional list recursively like this: 您可以像这样递归创建多维列表:

def MultiDimensionalList(instance, *dimensions):
    if len(dimensions) == 1:
      return list(
         instance() for i in xrange(
          dimensions[0]
        )
      )
    else:
      return list(
        MultiDimensionalList(instance, *dimensions[1:]) for i
        in xrange(dimensions[0])
      )

print MultiDimensionalList(lambda: None, 1, 1, 0)

[[]] [[]]

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

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