开发者

Python - Using the Multiply Operator to Create Copies of Objects in Lists [duplicate]

This question already has answers here: List of lists changes reflected across sublists unexpectedly (17 answers) Closed 8 years ago.

In Python, if I multiply of list of objects by an integer, I get a list of references to that object, e.g.:

>>> a = [[]] * 3
>>> a
[[], [], [开发者_运维知识库]]
>>> a[0].append(1)
>>> a
[[1], [1], [1]]

If my desired behavior is to create a list of copies of the original object (e.g. copies created by the "copy.copy()" method or something sort of standard, is there an elegant way to do this with the same multiplication operator? Or should I just stick with a list comprehension or something? E.g.

[[] for x in range(0,3)]

Any version of Python is fine.


This is a good usage of list comprehension - its also the most readable way to do it IMO.

So the [[] for x in range(0,3)] you suggest isn't the multiplication operator, but gets the result you want.


The multiplication operator on a sequence means repetition of the item(s) -- NOT creation of copies (shallow or deep ones) of the items. Nothing stops you from going crazy, a la:

import copy

class Crazy(object):
  def __init__(self, body, weird=copy.copy):
    self.gomez = body
    self.cousinitt = weird
  def __mul__(self, n):
    return [self.cousinitt(x) for x in (self.gomez * n)]

a = Crazy([[]]) * 3

...except your sanity and common sense, if any. Checking on those, how DID you dream operator * could be made to mean something utterly different than it's intended to mean, except by defining another class overloading __mul__ in weird ways...?-)


The list comprehension is the best way to do this. If you define a new class and overload the * operator, it will seriously confuse the next person to read the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜