在列表中重复列表X次 [英] Repeat a list within a list X number of times
问题描述
我正在做一个项目,因此我需要在列表中重复列表多次.显然,L.append(L)
只是在不创建单独列表的情况下再次添加了元素.我只是对如何使列表在大列表中分开感到困惑.
I'm working on a project and I need to repeat a list within a list a certain number of times. Obviously, L.append(L)
just adds the elements again without creating separate lists. I'm just stumped on how to make the lists separate within the big list.
简而言之,这就是我所拥有的:
In short form, this is what I have:
L = [1,2,3,4,5]
如果我想重复一遍,说3次,这样我就可以了:
If I wanted to to repeat it, say, 3 times so I'd have:
L = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
我该如何实现?我正在寻找大名单中的名单.
How do I achieve this? I'm looking for lists within the big list.
推荐答案
无需任何功能:
>>> L = [1,2,3,4,5]
>>> [L]*3
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
但是,您应该注意,如果您更改任何一个列表中的一个值,其他所有都将更改,因为它们引用了相同的对象.
However, you should note that if you change one value in any of the lists, all the others will change because they reference the same object.
>>> mylist = [L]*3
>>> mylist[0][0] = 6
>>> print mylist
[[6, 2, 3, 4, 5], [6, 2, 3, 4, 5], [6, 2, 3, 4, 5]]
>>> print L
[6, 2, 3, 4, 5]
为避免这种情况:
>>> L = [1,2,3,4,5]
>>> mylist = [L[:] for _ in range(3)]
>>> mylist[0][0] = 6
>>> print L
[1, 2, 3, 4, 5]
>>> print mylist
[[6, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
请注意L
的更改方式,只有mylist
中的第一个列表更改了.
Notice how L
didn't change, and only the first list in mylist
changed.
感谢评论中的每个人都对您有帮助:).
Thanks everyone in the comments for helping :).
这篇关于在列表中重复列表X次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!