我最近遇到了一段看起来像这样的python代码
groups = {}
for d, *v in dishes:
for x in v:
groups.setdefault(x, []).append(d)
Run Code Online (Sandbox Code Playgroud)
菜代表二维数组。1st for循环语句是什么意思?什么是* v?v之前的星号表示什么?使用变量之前,星号还有什么其他情况?
它本质上是元组/列表拆包和*args可迭代拆包的组合。每个可迭代对象在for循环的每次迭代中都被解压缩。
首先,让我们看一个简单的元组/列表解压缩:
>>> x, y = (1, 2)
>>> x
1
>>> y
2
# And now in the context of a loop:
>>> for x, y in [(1, 2), (3, 4)]:
>>> print(f'x={x}, y={y}')
"x=1, y=2"
"x=3, y=4"
Run Code Online (Sandbox Code Playgroud)
现在考虑以下内容(并想象与上面所示的循环相同的概念):
>>> x, y = (1, 2, 3)
ValueError: too many values to unpack (expected 2)
>>> x, *y = 1, 2, 3
>>> x
1
>>> y
[2, 3]
Run Code Online (Sandbox Code Playgroud)
注意如何*允许y消耗所有剩余的参数。
这类似于您*在函数中使用的方式-允许未指定数量的args,并消耗掉所有参数。您可以在此处查看更多(*args)用法示例。
>>> def foo(x, *args):
>>> print(x)
>>> print(args)
>>>foo(1, 2, 3, 4)
1
[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
对于实际示例,以下是一个快速示例:
>>> names = ("Jack", "Johnson", "Senior")
>>> fist_name, *surnames = names
>>> prin(surnames)
["Johnson", "Senior"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |