如何更改成员列表的内容更新复合列表?

时间:2016-09-09 16:53:35

标签: python list python-3.x data-structures

我们说我有:

friendlies = []
enemies = []
everyone = [friendlies + enemies]

我说:

friendlies.append("something")

所以友谊赛现在包含:

["something"]

什么是pythonic方式,以便everyone更新?因此,如果我按照上述方式更新friendlieseveryone将包含:

["something"] 

2 个答案:

答案 0 :(得分:3)

在复合列表中维护对friendliesenemies的引用:

everyone = [friendlies, enemies]
#                     ^

compisite列表的索引0和1将分别引用friendliesenemies

friendlies + enemies会创建一个不符合您要求的新列表。

更可读的方法是everyone字典:

everyone = {'friendlies': friendlies, 'enemies': enemies}

可以用作:

>>> friendlies = []
>>> enemies = []
>>> everyone = {'friendlies': friendlies, 'enemies': enemies}
>>> friendlies.append("something")
>>> everyone['friendlies']
['something']

答案 1 :(得分:2)

如果你现在总结,你会失去参考。创建列表以维护参考

Hacky的做法:

friendlies = []
enemies = []

everyone = [friendlies,enemies]  # not sum, sublists
enemies.append("something")
print(sum(everyone,[]))   # sum sublists to a new list