Python 赋值运算符中使用逗号和下划线的含义是什么?

发布于 2024-08-11 05:26:48 字数 647 浏览 9 评论 0原文

通读 Peter Norvig 的解决每个数独谜题文章,我遇到了一些我从未遇到过的 Python 习惯用法以前见过。

我知道函数可以返回值的元组/列表,在这种情况下,您可以将多个变量分配给结果,例如

def f():
    return 1,2

a, b = f()

但是以下各项的含义是什么?

d2, = values[s]  ## values[s] is a string and at this point len(values[s]) is 1

如果len(values[s]) == 1,那么此语句与d2 = value[s]有何不同?

关于在此处的赋值中使用下划线的另一个问题:

_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)

下划线是否具有基本上丢弃列表中返回的第一个值的效果?

Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.

I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as

def f():
    return 1,2

a, b = f()

But what is the meaning of each of the following?

d2, = values[s]  ## values[s] is a string and at this point len(values[s]) is 1

If len(values[s]) == 1, then how is this statement different than d2 = values[s]?

Another question about using an underscore in the assignment here:

_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)

Does the underscore have the effect of basically discarding the first value returned in the list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浮世清欢 2024-08-18 05:26:49

您可以在元组中使用尾随逗号,如下所示:

>>> (2,)*2
(2, 2)

>>> (2)*2
4

You can use the trailing comma in a tuple like this:

>>> (2,)*2
(2, 2)

>>> (2)*2
4
情话墙 2024-08-18 05:26:48

d2, = value[s]a,b=f() 类似,只是解包 1 个元素元组。

>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>> 

a 是元组,b 是整数。

d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.

>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>> 

a is tuple, b is an integer.

心作怪 2024-08-18 05:26:48

_ 与任何其他变量名称一样,但通常表示“我不关心这个变量”。

第二个问题:是“价值拆包”。当函数返回元组时,您可以解压其元素。

>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2

_ is like any other variable name but usually it means "I don't care about this variable".

The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.

>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
‖放下 2024-08-18 05:26:48

Python shell 中的 _ 也指最后一次操作的值。因此,

>>> 1
1
>>> _
1

逗号指的是元组拆包。所发生的情况是,返回值是一个元组,因此它被按照元组元素的顺序解压缩到用逗号分隔的变量中。

The _ in the Python shell also refers to the value of the last operation. Hence

>>> 1
1
>>> _
1

The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文