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

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!

解决方案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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值