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

编程入门 行业动态 更新时间:2024-10-25 04:20:13
本文介绍了在 Python 赋值运算符中使用逗号和下划线的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

通读 Peter Norvig 的 解决每篇数独谜题,我遇到了一些 Python 习语以前从未见过.

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

def f():返回 1,2a, b = f()

但以下每一项的含义是什么?

d2, = values[s] ## values[s] 是一个字符串,此时 len(values[s]) 是 1

如果len(values[s]) == 1,那么这个语句与d2 = values[s]有什么不同?

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

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

下划线是否有基本丢弃列表中返回的第一个值的作用?

解决方案

d2, = values[s]a,b=f() 一样,除了用于解包 1 个元素的元组.

<预><代码>>>>T=(1,)>>>a=T>>>一种(1,)>>>b,=T>>>乙1>>>

a 是元组,b 是整数.

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?

解决方案

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.

这篇关于在 Python 赋值运算符中使用逗号和下划线的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:58:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:下划线   赋值   逗号   运算符   含义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!