问题描述
假设我有一个给定的对象(一个字符串"a",一个数字-假设为0或一个列表['x','y']
)
我想创建一个包含该对象许多副本的列表,但不使用for循环:
L = ["a", "a", ... , "a", "a"]
或
L = [0, 0, ... , 0, 0]
或
L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]
我对第三种情况特别感兴趣.谢谢!
itertools.repeat()
是你的朋友.
L = list(itertools.repeat("a", 20)) # 20 copies of "a"
L = list(itertools.repeat(10, 20)) # 20 copies of 10
L = list(itertools.repeat(['x','y'], 20)) # 20 copies of ['x','y']
请注意,在第三种情况下,由于列表是通过引用引用的,因此更改列表中的['x','y']的一个实例将更改所有它们,因为它们都引用相同的列表. /p>
为避免引用同一项目,您可以改用理解来为每个列表元素创建新对象:
L = [['x','y'] for i in range(20)]
(对于Python 2.x,请使用xrange()
而不是range()
来提高性能.)
Suppose I have a given Object (a string "a", a number - let's say 0, or a list ['x','y']
)
I'd like to create list containing many copies of this object, but without using a for loop:
L = ["a", "a", ... , "a", "a"]
or
L = [0, 0, ... , 0, 0]
or
L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]
I'm especially interested in the third case. Thanks!
itertools.repeat()
is your friend.
L = list(itertools.repeat("a", 20)) # 20 copies of "a"
L = list(itertools.repeat(10, 20)) # 20 copies of 10
L = list(itertools.repeat(['x','y'], 20)) # 20 copies of ['x','y']
Note that in the third case, since lists are referred to by reference, changing one instance of ['x','y'] in the list will change all of them, since they all refer to the same list.
To avoid referencing the same item, you can use a comprehension instead to create new objects for each list element:
L = [['x','y'] for i in range(20)]
(For Python 2.x, use xrange()
instead of range()
for performance.)
这篇关于在Python中创建列表,并在一行中包含给定对象的多个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!