我有一个类实例 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
有任何想法吗?