Python:将项目追加到列表 N 次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4654414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Append item to list N times
提问by Toji
This seems like something Python would have a shortcut for. I want to append an item to a list N times, effectively doing this:
这似乎是 Python 的捷径。我想将一个项目附加到列表 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?
在那儿?
采纳答案by Amber
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]
回答by Mark Elliot
You could do this with a list comprehension
你可以用列表理解来做到这一点
l = [x for i in range(10)];
回答by Jake
Use extend to add a list comprehension to the end.
使用扩展在末尾添加列表理解。
l.extend([x for i in range(100)])
See the Python docsfor more information.
有关更多信息,请参阅Python 文档。
回答by kevpie
Itertools repeat combined with list extend.
Itertools 重复结合列表扩展。
from itertools import repeat
l = []
l.extend(repeat(x, 100))
回答by CTS_AE
I had to go another route for an assignment but this is what I ended up with.
我不得不走另一条路线来完成任务,但这就是我的结局。
my_array += ([x] * repeated_times)
回答by Rajan saha Raju
l = []
x = 0
l.extend([x]*100)

