[英]Python: Append item to list N times
This seems like something Python would have a shortcut for.这似乎是 Python 的捷径。 I want to append an item to a list N times, effectively doing this:
我想将一个项目附加到列表 N 次,有效地这样做:
l = []
x = 0
for i in range(100):
l.append(x)
It would seem to me that there should be an "optimized" method for that, something like:在我看来,应该有一个“优化”的方法,例如:
l.append_multiple(x, 100)
Is there?有吗?
For immutable data types:对于不可变数据类型:
l = [0] * 100
# [0, 0, 0, 0, 0, ...]
l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]
For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):对于通过引用存储的值,您可能希望稍后修改(如子列表或字典):
l = [{} for x in range(100)]
(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number>
syntax, and thus if you did something like [{}]*100
, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.) (第一种方法仅适用于常量值(如整数或字符串)的原因是因为在使用
<list>*<number>
语法时仅执行浅拷贝,因此如果您执行类似[{}]*100
,你最终会得到 100 个对同一个字典的引用——所以改变其中一个会改变它们。由于整数和字符串是不可变的,这对他们来说不是问题。)
If you want to add to an existing list, you can use the extend()
method of that list (in conjunction with the generation of a list of things to add via the above techniques):如果要添加到现有列表中,可以使用该列表的
extend()
方法(结合通过上述技术生成要添加的内容列表):
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
Use extend to add a list comprehension to the end.使用扩展在末尾添加列表理解。
l.extend([x for i in range(100)])
See the Python docs for more information.有关更多信息,请参阅Python 文档。
Itertools repeat combined with list extend. Itertools 重复结合列表扩展。
from itertools import repeat
l = []
l.extend(repeat(x, 100))
我不得不走另一条路线来完成任务,但这就是我的结局。
my_array += ([x] * repeated_times)
你可以用列表理解来做到这一点
l = [x for i in range(10)];
l = []
x = 0
l.extend([x]*100)
you can add any value like this for several times:您可以多次添加这样的任何值:
a = [1,2,3]
b = []
#if you want to add on item 3 times for example:
for i in range(len(a)):
j = 3
while j != 0:
b.append(a[i])
j-=1
#now b = [1,1,1,2,2,2,3,3,3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.