gpt4 book ai didi

python - 不在列表中 - 列表理解

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:15 24 4
gpt4 key购买 nike

我怎样才能像这样在列表理解中添加条件?例如:

例如:

[dict if dict not in THIS.LIST for dict in tempList]

最佳答案

顺序错了,把if移到最后

[dict for dict in tempList if dict not in THIS.LIST ]

使用你的方法 python 需要一个 else:

[dict if dict not in THIS.LIST else whatever for dict in tempList]

如果您想引用您正在创建的实际列表,请使用 for 循环,如果项目是可散列的,您可以使用集合来检查该元素是否已被 0(1) 查找,但如果你有字典,那么你将无法直接使用带有字典的集合:

res = [] 
for dct in temp_list:
if dct not in res:
res.append(dct)

或者使用列表组件的类似方法,从列表的开头检查到当前索引:

print([dct for ind, dct in enumerate(temp_list) if dct not in temp_list[:ind]])

如果您只想删除重复的字典,我们可以使用dict.items:

temp_list = [ {1:2},{1:2}]
print([dict(items) for items in set(tuple(dct.items()) for dct in temp_list) ])

或者使用 OrderedDict 来保持顺序:

from collections import OrderedDict
temp_list = [ {1:2},{1:2}]

print(list(OrderedDict(((tuple(dct.items()),dct) for dct in temp_list)).values()))

或者再次使用普通循环:

temp_list = [ {1:2},{1:2}]
seen = set()
out = []
for dct in temp_list:
tup = tuple(dct.items())
if tup not in seen:
out.append(dct)
seen.add(tup)
print(out)

关于python - 不在列表中 - 列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737389/

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