【发布时间】: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