gpt4 book ai didi

python - 有和没有parens的元组之间的区别?

转载 作者:太空宇宙 更新时间:2023-11-04 01:11:52 25 4
gpt4 key购买 nike

Elsewhere in the universe ,关于 tuple 周围括号的使用出现了一个问题。

"is there any advantage/disadvantage to declaring tuples by x = 1, 2 as opposed to x = (1, 2)? ... in regards to speed and memory allocation"

最佳答案

通常我会建议使用 timeit 凭经验评估速度,但这让我印象深刻,因为它确实是等价的东西。

果然,dis程序集确认了这一点:

这里是 x = 1, 2

  6           0 LOAD_CONST               3 ((1, 2))
3 STORE_FAST 2 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE

x = (1, 2):

  9           0 LOAD_CONST               3 ((1, 2))
3 STORE_FAST 2 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE

以防万一人们好奇相似性是否仅存在于由文字组成的元组中,我还做了x = a, b:

 12           0 LOAD_FAST                0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 STORE_FAST 2 (x)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE

x = (a, b):

 15           0 LOAD_FAST                0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 STORE_FAST 2 (x)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE

the source article 中所引用, Python 的 Fine Manual 涵盖了可选括号的主题:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).

让我们仔细看看为什么它们“经常......无论如何都是必要的” - 这是运算符优先级的问题。就像传统的书面算术有一个操作顺序一样,像 Python 这样的编程语言也是如此。它帮助我们区分 12 + 1/2(12 + 1)/2。所以在这种情况下,我们通常需要用括号括起 tuple 元素,这些元素比简单的 name 更复杂。或 literal .所以我们可以在下面的这些例子中看到两种不同的解释使用元组的表达式的方式。由于逗号的优先级低于乘法运算符(并且它们的结合性相同),因此当没有括号以提供更明确的顺序时,乘法首先发生。

>>> 12 * 4, 5
(48, 5)
>>> 12 * (4, 5)
(4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5)

关于括号和元组的脚注,也来自 The Fine Manual :

The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

资源:https://gist.github.com/androm3da/8a646fbe817d576b1f0d

关于python - 有和没有parens的元组之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27210104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com