复制列表中的元素 [英] replicating elements in list
本文介绍了复制列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这个
b = 3
l = [1, 2]
我想修改l,以便每个元素出现与b一样多的次数.这样:
I want to modify l so that each element appears as many times as b. So that:
l = [1, 1, 1, 2, 2, 2]
我用了这个:
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.
推荐答案
我的2美分:
另一种实现此目的的方法是利用您可以在Python中将列表相乘的事实.
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]
只需调用sorted
函数即可对其进行排序:
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]
这篇关于复制列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文