编辑:正如@BrenBarn指出的那样,原始文本没有意义。
给定一个字典列表(由csv.DictReader
提供--它们都有str
键和值),通过将它们全部放入集合中来删除重复项是很好的,但是由于dict
不可哈希,因此不能直接这样做。一些现有 问题 探讨了如何为集合/字典伪造__hash__()
,但没有解决应该选择哪种方式的问题。
# i. concise but ugly round trip
filtered = [eval(x) for x in {repr(d) for d in pile_o_dicts}]
# ii. wordy but avoids round trip
filtered = []
keys = set()
for d in pile_o_dicts:
key = str(d)
if key not in keys:
keys.add(key)
filtered.append(d)
# iii. introducing another class for this seems Java-like?
filtered = {hashable_dict(x) for x in pile_o_dicts}
# iv. something else entirely
在Python之禅的精神中,有什么“显而易见的方法”来完成它?
{repr(d):d for d in pile_o_dicts}.values()
,而不是使用set + evals的列表推导式。 - jdi