是否有没有值的 Python 字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19454970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:47:12  来源:igfitidea点击:

Is there a Python dict without values?

pythondictionary

提问by nucleartide

Instead of this:

取而代之的是:

a = {"foo": None, "bar": None}

Is there a way to write this?

有没有办法写这个?

b = {"foo", "bar"}

And still let bhave constant time access (i.e. not a Python set, which cannot be keyed into)?

并且仍然允许b持续时间访问(即不是 Python 集,无法键入)?

采纳答案by nneonneo

Actually, in Python 2.7 and 3.2+, this really does work:

实际上,在 Python 2.7 和 3.2+ 中,这确实有效:

>>> b = {"foo", "bar"}
>>> b
set(['foo', 'bar'])

You can't use []access on a set ("key into"), but you can test for inclusion:

您不能[]在集合上使用访问权限(“key into”),但您可以测试是否包含:

>>> '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)}

回答by Ashwini Chaudhary

Yes, sets:

是的,sets

set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.

Related: How is set() implemented?

相关:set() 是如何实现的?

Time complexity : https://wiki.python.org/moin/TimeComplexity#set

时间复杂度:https: //wiki.python.org/moin/TimeComplexity#set

回答by Claudiu

In order to "key" into a set in constant time use in:

为了在恒定时间内“键”成一个集合,请使用in

>>> s = set(['foo', 'bar', 'baz'])
>>> 'foo' in s
True
>>> 'fork' in s
False