2

我有一个类实例 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

有任何想法吗?

4

2 回答 2

0

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

for child, toy in zip(child_list, new_toys):
    child.toy = toy
    print "%s has toy %s" %(child.name, child.toy)
于 2017-04-12T08:58:25.983 回答
0

如果你真的想使用列表推导,你应该创建一个新列表来创建新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循环。

于 2017-04-12T09:01:53.470 回答