gpt4 book ai didi

python - 迭代列表元素的字典

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:40 25 4
gpt4 key购买 nike

我对 Python (2.x) 非常陌生,并试图了解如何迭代包含多个列表的字典:

dict = {'list_1':[3, 'green', 'yellow', 'black'], 'list_2':[2, 'green', 'blue']}

我试图创建一个包含这些列表的所有唯一值的新列表,但忽略第一项(整数)。我正在寻找的结果是:

['green', 'yellow', 'black', 'blue']

这是我的众多尝试之一。我很迷茫,所以如果有人能解释我将不胜感激。

newlist = []
for colors in dict.values() [1:]:
if not colors in newlist:
newlist.append(colors)

最佳答案

使用set.union:

>>> dic = {'list_1':[3, 'green', 'yellow', 'black'], 'list_2':[2, 'green', 'blue']}
>>> set().union(*(x[1:] for x in dic.itervalues()))
set(['blue', 'black', 'green', 'yellow'])

如果需要列表,只需将此集合传递给 list()

您尝试的工作版本,尽管效率不高;

newlist = []
for colors in dic.values():
lis = colors[1:] #do slicing here
for item in lis:
if item not in newlist:
newlist.append(item)
print newlist #['green', 'blue', 'yellow', 'black']

关于python - 迭代列表元素的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18228727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com