首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python:基于来自另一个列表变量的相同类实例更新一个列表变量中的类实例

Python:基于来自另一个列表变量的相同类实例更新一个列表变量中的类实例
EN

Stack Overflow用户
提问于 2014-04-04 18:58:05
回答 1查看 51关注 0票数 0

有两个列表变量: listA和listB。这两个列表都存储三个MyClass实例。listA和listB的区别在于,listB的实例将其self.attrA设置为"myValue“。在脚本的末尾,我循环遍历listA和listB,以检查它们的实例self.id属性是否匹配。如果需要,我希望用相应的listA实例来更新(覆盖) listB实例(因此listA实例都将其self.myAttr设置为"myValue“)。奇怪的是,即使listA实例设置为相等,它们仍然保持不变:

代码语言:javascript
复制
inst_A = inst_B

哪里出错了?

代码语言:javascript
复制
class MyClass(object):
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.id=None
        self.attrA=None
        if 'id' in arg.keys(): 
            self.id=arg['id']
        if 'attrA' in arg.keys(): 
            self.attrA=arg['attrA']

listA=[]
for i in range(3): 
    listA.append( MyClass({'id':i}))

listB=[]
for i in range(3): 
    listB.append( MyClass({'id':i, 'attrA':'myValue'}))

for inst_A in listA:
    for inst_B in listB:
        if inst_A.id==inst_B.id:
            inst_A=inst_B

for inst_A in listA:
    print inst_A.attrA  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-04 19:25:49

for循环不是在变异列表,而是在变异迭代变量。

代码语言:javascript
复制
for inst_A in listA: # this creates a new name called inst_A which points
                     # to a value in listA
    for inst_B in listB:
        if inst_A.id == inst_B.id:
            # this assignment changes the inst_A name to now point to inst_B
            inst_A = inst_B

    # At the bottom of the loop, inst_A is recycled, so the value it was 
    # assigned to (inst_B) is forgotten

尝试:

代码语言:javascript
复制
for i in range(len(listA)): 
    for inst_B in listB:
        if listA[i].id == inst_B.id:
            # almost the same as above, except here we're changing the value
            # of the i-th entry in listA
            listA[i] = inst_B
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22870935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档