我们说我有:
friendlies = []
enemies = []
everyone = [friendlies + enemies]
我说:
friendlies.append("something")
所以友谊赛现在包含:
["something"]
什么是pythonic方式,以便everyone
更新?因此,如果我按照上述方式更新friendlies
,everyone
将包含:
["something"]
答案 0 :(得分:3)
在复合列表中维护对friendlies
和enemies
的引用:
everyone = [friendlies, enemies]
# ^
compisite列表的索引0和1将分别引用friendlies
和enemies
。
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