replicating elements in list

痴心易碎 提交于 2019-11-28 10:05:13

问题


Say I have this

b = 3
l = [1, 2]

I want to modify l so that each element appears as many times as b. So that:

l = [1, 1, 1, 2, 2, 2]

I used this:

for x in l:
  for m in range(b):
    l.append(x)

But it resulted in an infinite loop. Any help would be appreciated. I would prefer you guys to give ideas rather than give me the code. Thanks.


回答1:


My 2 cents :

Another way to achieve this would also be to take advantage of the fact you can multiply lists in Python.

>>> l = [1, 2, 3]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

A simple call to the sorted function allows to sort it back :

>>> b = 3    
>>> l = [1, 2]
>>> sorted(l * b)
[1, 1, 1, 2, 2, 2]



回答2:


You can use a list comprehension:

>>> b = 3
>>> x = [1, 2]
>>> l = [x for x in l for _ in range(b)]
>>> l
[1, 1, 1, 2, 2, 2]
>>>

Now, to fix your issue:

You might want to create a new list, and append to that list

>>> l  = [1, 2]
>>> y = []
>>> b = 3
>>> for x in l:
...   for i in range(b):
...     y.append(x)
...
>>> y
[1, 1, 1, 2, 2, 2]

I would prefer the list comprehension method though.




回答3:


Your main problem is that it's unsafe to modify the list as you iterate over it. You could work around that by building a new list - the various itertools and comprehension answers show some ways to do that, or you could just use your for loop if you like.

Since you asked for ideas rather than code, I'll point out that itertools.repeat is another useful tool. It should be fairly obvious how to use that to multiply a given element of the list - you'd then need to figure out how to combine the iterators for each element of your list into a single list. For that, itertools.chain is useful, using either the * syntax to unpack a sequence of repeat iterators or the itertools.chain.from_iterable constructor.

This would essentially be the same idea as freyrs' answer, just creating a repeat iterator for each element rather than creating and multiplying a list for each element.




回答4:


Can use itertools for this:

from itertools import chain
list(chain(*[[i]*b for i in l]))

Which gives output:

[1, 1, 1, 2, 2, 2]


来源:https://stackoverflow.com/questions/20276138/replicating-elements-in-list

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