Append a new item to a list within a list

杀马特。学长 韩版系。学妹 提交于 2019-12-10 12:59:13

问题


I'm trying to append a new float element to a list within another list, for example:

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.


回答1:


lst = [[] for _ in xrange(2)] (or just [[], []]). Don't use multiplication with mutable objects — you get the same one X times, not X different ones.




回答2:


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

dont call it list, that will prevent you from calling the built-in function list().

The reason that your problem happens is that Python creates one list then repeats it twice. 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.




回答3:


You can do in simplest way....

>>> list = [[]]*2
>>> list[1] = [2.5]
>>> list
[[], [2.5]]



回答4:


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

or

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



回答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:

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

The solution is to have 2 inner lists, list = [[], []]




回答6:


As per @Cat Plus Plus dont use multiplication.I tried without it.with same your code.

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



回答7:


you should write something like this:

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



回答8:


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)

[[]]



来源:https://stackoverflow.com/questions/6814727/append-a-new-item-to-a-list-within-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!