gpt4 book ai didi

python - 列表理解,检查项目是否唯一

转载 作者:IT老高 更新时间:2023-10-28 22:13:04 26 4
gpt4 key购买 nike

我正在尝试编写一个列表理解语句,如果它当前不包含在列表中,它将只添加一个项目。有没有办法检查当前正在构建的列表中的当前项目?下面是一个简单的例子:

输入

{
"Stefan" : ["running", "engineering", "dancing"],
"Bob" : ["dancing", "art", "theatre"],
"Julia" : ["running", "music", "art"]
}

输出

["running", "engineering", "dancing", "art", "theatre", "music"]

不使用列表理解的代码

output = []
for name, hobbies in input.items():
for hobby in hobbies:
if hobby not in output:
output.append(hobby)

我的尝试

[hobby for name, hobbies in input.items() for hobby in hobbies if hobby not in ???]

最佳答案

您可以使用 set 并设置理解:

{hobby for name, hobbies in input.items() for hobby in hobbies}

作为 m.wasowski mentioned ,我们这里不使用name,所以可以使用item.values()代替:

{hobby for hobbies in input.values() for hobby in hobbies}

如果你真的需要一个列表作为结果,你可以这样做(但请注意,通常你可以毫无问题地使用集合):

list({hobby for hobbies in input.values() for hobby in hobbies})

关于python - 列表理解,检查项目是否唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331907/

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