Repeat a list within a list X number of times

♀尐吖头ヾ 提交于 2019-12-17 21:14:20

问题


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]

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.


回答1:


No need for any functions:

>>> 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]

To avoid this:

>>> 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]]

Notice how L didn't change, and only the first list in mylist changed.

Thanks everyone in the comments for helping :).



来源:https://stackoverflow.com/questions/16095865/repeat-a-list-within-a-list-x-number-of-times

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