Append a new item to a list within a list

2019-06-18 04:10发布

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.

8条回答
你好瞎i
2楼-- · 2019-06-18 04:15

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.

查看更多
走好不送
3楼-- · 2019-06-18 04:17

You can do in simplest way....

>>> list = [[]]*2
>>> list[1] = [2.5]
>>> list
[[], [2.5]]
查看更多
太酷不给撩
4楼-- · 2019-06-18 04:19

you should write something like this:

>>> l = [[] for _ in xrange(2)]
>>> l[1].append(2.5)
>>> l
[[], [2.5]]
查看更多
We Are One
5楼-- · 2019-06-18 04:32
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.

查看更多
劫难
6楼-- · 2019-06-18 04:32
list = [[]]
list.append([2.5])

or

list = [[],[]]
list[1].append(2.5)
查看更多
看我几分像从前
7楼-- · 2019-06-18 04:37

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]]
查看更多
登录 后发表回答