为什么有时可以用 {} 替换 set()? [英] Why is it possible to replace sometimes set() with {}?

查看:34
本文介绍了为什么有时可以用 {} 替换 set()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PyCharm 中,当我写:

return set([(sy + ady, sx + adx)])

它说函数调用可以用设置文字替换"所以它用:

return {(sy + ady, sx + adx)}

这是为什么?Python 中的 set() 与字典 {} 不一样?

如果它想优化这个,为什么它更有效?

解决方案

Python 集合和字典都可以使用花括号构建:

my_dict = {'a': 1, 'b': 2}

my_set = {1, 2, 3}

解释器(和人类读者)可以根据它们的内容区分它们.但是,无法区分空集和空字典,因此在这种情况下,您需要使用 set() 来消除空集的歧义.

一个非常简单的测试表明文字构造速度更快(python3.5):

<预><代码>>>>timeit.timeit('a = set([1, 2, 3])')0.5449375328607857>>>timeit.timeit('a = {1, 2, 3}')0.20525191631168127

这个问题涵盖了文字构造相对于内置函数的一些性能问题,尽管对于列表和字典.总结起来似乎是字面结构需要解释器的工作更少.

In PyCharm, when I write:

return set([(sy + ady, sx + adx)])

it says "Function call can be replaced with set literal" so it replaces it with:

return {(sy + ady, sx + adx)}

Why is that? A set() in Python is not the same as a dictionary {}?

And if it wants to optimize this, why is this more effective?

解决方案

Python sets and dictionaries can both be constructed using curly braces:

my_dict = {'a': 1, 'b': 2}

my_set = {1, 2, 3}

The interpreter (and human readers) can distinguish between them based on their contents. However it isn't possible to distinguish between an empty set and an empty dict, so this case you need to use set() for empty sets to disambiguate.

A very simple test suggests that the literal construction is faster (python3.5):

>>> timeit.timeit('a = set([1, 2, 3])')
0.5449375328607857
>>> timeit.timeit('a = {1, 2, 3}')
0.20525191631168127

This question covers some issues of performance of literal constructions over builtin functions, albeit for lists and dicts. The summary seems to be that literal constructions require less work from the interpreter.

这篇关于为什么有时可以用 {} 替换 set()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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