是否有没有值的Python字典? [英] Is there a Python dict without values?
本文介绍了是否有没有值的Python字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代替此:
a = {"foo": None, "bar": None}
有没有办法写这个?
b = {"foo", "bar"}
b
具有恒定的访问时间(即没有Python集,无法键入)?
And still let b
have constant time access (i.e. not a Python set, which cannot be keyed into)?
推荐答案
实际上,在Python 2.7和3.2+中,这确实有效:
Actually, in Python 2.7 and 3.2+, this really does work:
>>> b = {"foo", "bar"}
>>> b
set(['foo', 'bar'])
你不能使用 []
访问集合(键入),但是您可以测试是否包含:
You can't use []
access on a set ("key into"), but you can test for inclusion:
>>> 'x' in b
False
>>> 'foo' in b
True
集合与无价值字典一样接近得到。它们具有平均情况下的恒定时间访问权限,需要可散列的对象(即,没有存储列表或集合中的字典),甚至还支持它们自己的理解语法:
Sets are as close to value-less dictionaries as it gets. They have average-case constant-time access, require hashable objects (i.e. no storing lists or dicts in sets), and even support their own comprehension syntax:
{x**2 for x in xrange(100)}
这篇关于是否有没有值的Python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文