在Python中创建一个列表,在一行中包含给定对象的多个副本

时间:2010-05-07 03:10:41

标签: python list

假设我有一个给定的对象(一个字符串“a”,一个数字 - 比方说0或列表['x','y']

我想创建包含此对象的许多副本的列表,但不使用for循环:

L = ["a", "a", ... , "a", "a"]

L = [0, 0, ... , 0, 0]

L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]

我对第三种情况特别感兴趣。 谢谢!

6 个答案:

答案 0 :(得分:39)

您可以使用*运算符:

L = ["a"] * 10
L = [0] * 10
L = [["x", "y"]] * 10

小心这创建相同项目的N个副本,这意味着在第三种情况下,您创建一个包含N个["x", "y"]列表引用的列表;例如,更改L[0][0]也会修改所有其他副本:

>>> L = [["x", "y"]] * 3
>>> L
[['x', 'y'], ['x', 'y'], ['x', 'y']]
>>> L[0][0] = "z"
[['z', 'y'], ['z', 'y'], ['z', 'y']]

在这种情况下,您可能希望使用列表解析:

L = [["x", "y"] for i in range(10)]

答案 1 :(得分:30)

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()以提高性能。)

答案 2 :(得分:2)

您可以执行类似

的操作
x = <your object>
n = <times to be repeated>
L = [x for i in xrange(n)]

Python 3的替换范围(n)。

答案 3 :(得分:0)

如果您想要golf的唯一实例,那么(稍微)会更短:

from turtle import Turtle, Screen

def move_pokey():
    pokey.forward(10)
    x, y = pokey.position()

    if not (-width/2 < x < width/2 and -height/2 < y < height/2):
        pokey.undo()
        pokey.left(90)

    screen.ontimer(move_pokey, 100)

hokey = Turtle(shape="turtle")
hokey.color("red")
hokey.penup()

pokey = Turtle(shape="turtle")
pokey.setheading(30)
pokey.color("green")
pokey.penup()

screen = Screen()

width = screen.window_width()
height = screen.window_height()

screen.onkey(lambda: hokey.forward(10), "Up")
screen.onkey(lambda: hokey.left(45), "Left")
screen.onkey(lambda: hokey.right(45), "Right")
screen.onkey(lambda: hokey.back(10), "Down")
screen.onkey(screen.bye, "q")

screen.listen()

screen.ontimer(move_pokey, 100)

screen.mainloop()

疯狂的是,它(也明显)更快:

L = [['x', 'y'] for _ in []*10]

答案 4 :(得分:0)

我希望这对某人有帮助。我想将字典的多个副本添加到列表中并提出:

>>> myDict = { "k1" : "v1" }
>>> myNuList = [ myDict.copy() for i in range(6) ]
>>> myNuList
[{'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]
>>> myNuList[1]['k1'] = 'v4'
>>> myNuList
[{'k1': 'v3'}, {'k1': 'v4'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]

我发现:

>>> myNuList = [ myDict for i in range(6) ]

没有复制该字典的新副本。

答案 5 :(得分:0)

如果您要创建一个list并插入重复元素 tuple unpacking会派上用场:

l = ['a', *(5*['b']), 'c']
l
Out[100]: ['a', 'b', 'b', 'b', 'b', 'b', 'c']

[the docs]