dict和set之间的区别(python) [英] Difference between dict and set (python)

查看:229
本文介绍了dict和set之间的区别(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我知道这一点,

a = {}  # dict

构造一个空字典.现在,我也意识到了这一点,

Constructs an empty dictionary. Now, I also picked up that this,

b = {1, 2, 3}  # set

创建一个集合.

>>>print(type(a))
<class 'dict'>

>>>print(type(b))
<class 'set'>

虽然我了解它的作用,但看不到为什么我们对集合和字典使用相同的语法.我试图在 set dict 部分,但可悲的是,我一无所有.

While I understand what it does, I fail to see why we use the same syntax for both sets and dictionaries. I tried to find some more information about the logic behind this in the set and dict sections of the manual, but sadly, I got nothing out of it.

有人可以向我解释为什么我们这样做吗?是出于历史原因,还是我明显地遗漏了一些东西?

Could anyone explain to me why we do this in this way? Is it for historical reasons, or am I missing something blatantly obvious?

推荐答案

Python 2中没有 set文字,历史上大括号仅用于字典.可以从列表(或任何可迭代对象)中产生集合:

There were no set literals in Python 2, historically curly braces were only used for dictionaries. Sets could be produced from lists (or any iterables):

set([1, 2, 3])
set([i for i in range(1, 3)])

Python 3引入了集合文字和理解(请参见 PEP-3100 ),这使我们可以避免使用中间列表:

Python 3 introduced set literals and comprehensions (see PEP-3100) which allowed us to avoid intermediate lists:

{1, 2, 3}
{i for i in range(1, 3)}

但是,由于向后兼容,空集形式保留给字典使用.来自 [Python-3000]在P3K中的引用?状态:

The empty set form, however, was reserved for dictionaries due to backwards compatibility. References from [Python-3000] sets in P3K? states:

我确定我们可以解决问题---我同意,{}表示空集,而{:} 空的字典将是理想的,如果不是为了向后兼容.一世 我第一次写PEP时喜欢特殊的空对象"的想法(即, 有{}可能会变成set或dict的东西,但是一个 的讲师说服我,这只会导致混乱 在新来者的心中(以及实施的痛苦).

I'm sure we can work something out --- I agree, {} for empty set and {:} for empty dict would be ideal, were it not for backward compatibility. I liked the "special empty object" idea when I first wrote the PEP (i.e., have {} be something that could turn into either a set or dict), but one of the instructors here convinced me that it would just lead to confusion in newcomers' minds (as well as being a pain to implement).

以下消息更好地描述了以下规则:

The following message describes these rules better:

我认为Guido是最好的解决方案.将set()用于空集,使用{} 对于空的字典,请使用{genexp}进行设置的理解/显示,请使用 {1,2,3}用于显式集合文字,而{k1:v1, k2:v2}用于dict 文字.如果需求超出需求,我们以后总是可以添加{/}.

I think Guido had the best solution. Use set() for empty sets, use {} for empty dicts, use {genexp} for set comprehensions/displays, use {1,2,3} for explicit set literals, and use {k1:v1, k2:v2} for dict literals. We can always add {/} later if demand exceeds distaste.

这篇关于dict和set之间的区别(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆