【问题标题】:Assign multiple returns of a function to the attributes of instances in a list将函数的多个返回分配给列表中实例的属性
【发布时间】:2017-04-12 08:50:31
【问题描述】:

我有一个 Child 类实例列表,我想使用函数返回的玩具列表修改每个孩子的玩具属性

下面有一个可行的解决方案,但我想知道是否有单线?

import random

class Child():
    def __init__(self, name, toy):
        self.name = name
        self.toy = toy

def change_toys(nChildren):
    toys = ['toy1', 'toy2', 'toy3', 'toy4']
    random.shuffle(toys)
    return toys[:nChildren]

child_list = [Child('Ngolo', None), Child('Kante', None)]

new_toys = change_toys(len(child_list))

for i in range(len(child_list)):
    child_list[i].toy = new_toys[i]
    print "%s has toy %s" %(child_list[i].name, child_list[i].toy)

输出(随机玩具分配):

Ngolo has toy toy3
Kante has toy toy2

我试过了:

[child.toy for child in child_list] = change_toys(nChildren)

但这不起作用,我明白了

SyntaxError: can't assign to list comprehension

有什么想法吗?

【问题讨论】:

  • 如果您的工作解决方案有效,请坚持下去。有时你仍然需要编写for 循环。
  • 您不应该使用列表推导来解决副作用。坚持常规循环。另请注意,您可以random.sample 简化change_toys。
  • 如果您的解决方案有效,您应该将问题发布到codereview.stackexchange.com

标签: python class multiple-assignment


【解决方案1】:

这不会是单行的,但您应该通过避免使用索引i,以更简洁、更 Pythonic 的方式编写循环:

for child, toy in zip(child_list, new_toys):
    child.toy = toy
    print "%s has toy %s" %(child.name, child.toy)

【讨论】:

    【解决方案2】:

    如果您真的想要使用列表推导式,您应该创建一个新列表创建新的Child 对象,而不是改变现有对象:

    In [6]: new_list = [Child(c.name, toy) for c, toy in zip(child_list, change_toys(len(child_list)))]
    
    In [7]: new_list
    Out[7]: [<__main__.Child at 0x103ade208>, <__main__.Child at 0x103ade1d0>]
    
    In [8]: c1, c2 = new_list
    
    In [9]: c1.name, c1.toy, c2.name, c2.toy
    Out[9]: ('Ngolo', 'toy4', 'Kante', 'toy2')
    

    与原始列表相比:

    In [10]: c1, c2 = child_list
    
    In [11]: c1.name, c1.toy, c2.name, c2.toy
    Out[11]: ('Ngolo', None, 'Kante', None)
    

    如果您宁愿坚持改变您的子实例(一种合理的方法),那么您的 for 循环就可以了。

    我会使用zip 像@ThierryLathuille 回答一样使用for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2019-05-27
      • 2011-10-30
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多