Jas*_* Tu 19 python dictionary
而不是这个:
a = {"foo": None, "bar": None}
Run Code Online (Sandbox Code Playgroud)
有没有办法写这个?
b = {"foo", "bar"}
Run Code Online (Sandbox Code Playgroud)
并且仍然允许b持续时间访问(即不是Python集,无法键入)?
nne*_*neo 24
实际上,在Python 2.7和3.2+中,这确实有效:
>>> b = {"foo", "bar"}
>>> b
set(['foo', 'bar'])
Run Code Online (Sandbox Code Playgroud)
您不能[]在集合上使用访问权限("key into"),但您可以测试是否包含:
>>> 'x' in b
False
>>> 'foo' in b
True
Run Code Online (Sandbox Code Playgroud)
集合尽可能接近无值字典.它们具有平均情况下的常量时间访问,需要可清除对象(即没有存储列表或集合中的dicts),甚至支持他们自己的理解语法:
{x**2 for x in xrange(100)}
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 18
是的,sets:
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
Run Code Online (Sandbox Code Playgroud)
相关:如何实现set()?
时间复杂度:https://wiki.python.org/moin/TimeComplexity#set