Python-使用乘法运算符在列表中创建对象的副本 [英] Python - Using the Multiply Operator to Create Copies of Objects in Lists

查看:93
本文介绍了Python-使用乘法运算符在列表中创建对象的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果我将对象列表乘以整数,则会得到对该对象的引用列表,例如:

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]]

如果我想要的行为是创建原始对象的副本列表(例如,通过"copy.copy()"方法或某种标准创建的副本),是否有一种优雅的方式要使用相同的乘法运算符 来执行此操作还是我应该坚持使用列表理解之类的方法?例如

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)]

任何版本的Python都可以.

Any version of Python is fine.

推荐答案

序列上的乘法运算符表示项目的重复-不会创建项目的副本(浅副本或深副本).没什么可阻止您发疯的,啦:

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

...除了您的理智和常识(如果有).进行检查,如何使梦想的操作符*的DID含义与预期的含义完全不同,除了以怪异的方式定义另一个重载__mul__的类...?-)

...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...?-)

这篇关于Python-使用乘法运算符在列表中创建对象的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆