Python 创建重复 N 次的单个项目列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3459098/
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
Create list of single item repeated N times
提问by chimeracoder
I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated ntimes (where n= length of the list).
我想创建一系列长度各不相同的列表。每个列表将包含相同的元素e,重复n次数(其中n= 列表的长度)。
How do I create the lists, without using a list comprehension [e for number in xrange(n)]for each list?
如何创建列表,而不[e for number in xrange(n)]对每个列表使用列表理解?
采纳答案by Mark Byers
You can also write:
你也可以写:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
您应该注意,例如,如果 e 是一个空列表,您将获得一个包含对同一列表的 n 个引用的列表,而不是 n 个独立的空列表。
Performance testing
性能测试
At first glance it seemsthat repeat is the fastest way to create a list with n identical elements:
乍一看,repeat似乎是创建具有 n 个相同元素的列表的最快方法:
>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819
But wait - it's not a fair test...
但是等等 - 这不是一个公平的测试......
>>> itertools.repeat(0, 10)
repeat(0, 10) # Not a list!!!
The function itertools.repeatdoesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:
该函数itertools.repeat实际上并不创建列表,它只是创建一个对象,如果您愿意,可以使用该对象创建列表!让我们再试一次,但转换为列表:
>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233
So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.
因此,如果您想要一个列表,请使用[e] * n. 如果要懒惰地生成元素,请使用repeat.
回答by Jochen Ritzel
Itertools has a function just for that:
Itertools 有一个功能:
import itertools
it = itertools.repeat(e,n)
Of course itertoolsgives you a iterator instead of a list. [e] * ngives you a list, but, depending on what you will do with those sequences, the itertoolsvariant can be much more efficient.
当然itertools给你一个迭代器而不是一个列表。[e] * n为您提供了一个列表,但是,根据您将如何处理这些序列,该itertools变体可能会更有效率。
回答by gaefan
>>> [5] * 4
[5, 5, 5, 5]
Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list!
当重复的项目是一个列表时要小心。列表不会被克隆:所有元素都将引用同一个列表!
>>> x=[5]
>>> y=[x] * 4
>>> y
[[5], [5], [5], [5]]
>>> y[0][0] = 6
>>> y
[[6], [6], [6], [6]]
回答by Mad Scientist
[e] * n
should work
应该管用
回答by Aaron Hall
Create List of Single Item Repeated n Times in Python
在 Python 中创建重复 n 次的单个项目列表
Immutable items
不可变项
For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:
对于不可变的项目,比如 None、bool、int、浮点数、字符串、元组或frozensets,你可以这样做:
[e] * 4
Note that this is best only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.
请注意,这最好仅与列表中的不可变项(字符串、元组、冻结集)一起使用,因为它们都指向内存中同一位置的同一项。当我必须构建一个包含所有字符串模式的表时,我经常使用它,这样我就不必给出高度冗余的一对一映射。
schema = ['string'] * len(columns)
Mutable items
可变项目
I've used Python for a long time now, and I have never seen a use-case where I would do the above with a mutable instance. Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:
我已经使用 Python 很长时间了,我从来没有见过一个用例,我会用一个可变实例来做上面的事情。相反,要获得一个可变的空列表、集合或字典,您应该执行以下操作:
list_of_lists = [[] for _ in columns]
The underscore is simply a throwaway variable name in this context.
在这种情况下,下划线只是一个一次性变量名。
If you only have the number, that would be:
如果你只有号码,那就是:
list_of_lists = [[] for _ in range(4)]
The _is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.
该_不是真的很特别,但你的编码环境风格检查可能会抱怨,如果你不打算使用的变量和使用的其他任何名称。
Caveats for using the immutable method with mutable items:
对可变项使用不可变方法的注意事项:
Beware doing this with mutable objects, when you change one of them, they all change because they're all the sameobject:
当你对可变对象这样做时要小心,当你改变其中一个对象时,它们都会改变,因为它们都是同一个对象:
foo = [[]] * 4
foo[0].append('x')
foo now returns:
foo 现在返回:
[['x'], ['x'], ['x'], ['x']]
But with immutable objects, you can make it work because you change the reference, not the object:
但是对于不可变对象,您可以使其工作,因为您更改了引用,而不是对象:
>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]
>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]
But again, mutable objects are no good for this, because in-place operations change the object, not the reference:
但同样,可变对象对此没有好处,因为就地操作更改了对象,而不是引用:
l = [set()] * 4
>>> l[0] |= set('abc')
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]
回答by W.P. McNeill
As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.
正如其他人指出的那样,对可变对象使用 * 运算符会重复引用,因此如果您更改一个引用,则会将它们全部更改。如果你想创建一个可变对象的独立实例,你的 xrange 语法是最 Pythonic 的方式来做到这一点。如果您对一个从未使用过的命名变量感到困扰,您可以使用匿名下划线变量。
[e for _ in xrange(n)]

