Python Dict vs List仅用于添加唯一元素

0 python coding-style

为了实现可迭代的独特元素,[2]是否可以接受?

# [1]
if element not in list:
    list.append(element)

# [2]
dict[element] = None # value doesn't matter
Run Code Online (Sandbox Code Playgroud)

pio*_*kuc 7

使用set作为您的数据结构.

列表不是很好的性能,检查元素是否在列表中需要线性时间.列表越长,它越慢.

Set具有持续的查找时间.字典也是如此,但你不需要键值对,所以它更优雅:

s = set()
s.add(element)
Run Code Online (Sandbox Code Playgroud)

s = {}
s[element] = None
Run Code Online (Sandbox Code Playgroud)

另外,您可以获得所有不错的设置操作,例如union,intersection等.请参阅文档.