heL*_*maN 18 python tuples namedtuple python-3.x iterable-unpacking
正如PythonCookbook中提到的,*
可以在元组之前添加,*
这里的意思是什么?
第1.18章.将名称映射到序列元素:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
s = Stock(*rec)
# here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45)
Run Code Online (Sandbox Code Playgroud)
在同一部分,**dict
提出:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
Run Code Online (Sandbox Code Playgroud)
什么是**
这里的功能?
Ela*_*zar 41
*t
表示"将此元组的元素视为此函数调用的位置参数."
def foo(x, y):
print(x, y)
>>> t = (1, 2)
>>> foo(*t)
1 2
Run Code Online (Sandbox Code Playgroud)
从v3.5开始,你也可以在list/tuple/set literals中执行此操作:
>>> [1, *(2, 3), 4]
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
**d
表示"将字典中的键值对视为此函数调用的附加命名参数."
def foo(x, y):
print(x, y)
>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2
Run Code Online (Sandbox Code Playgroud)
从v3.5开始,您也可以在字典文字中执行此操作:
>>> d = {'a': 1}
>>> {'b': 2, **d}
{'b': 2, 'a': 1}
Run Code Online (Sandbox Code Playgroud)
*t
表示"获取此函数的所有其他位置参数,并将它们作为元组打包到此参数中."
def foo(*t):
print(t)
>>> foo(1, 2)
(1, 2)
Run Code Online (Sandbox Code Playgroud)
**d
表示"获取此函数的所有其他命名参数,并将它们作为字典条目插入此参数中."
def foo(**d):
print(d)
>>> foo(x=1, y=2)
{'y': 2, 'x': 1}
Run Code Online (Sandbox Code Playgroud)
for
循环中*x
意味着"消耗右侧的其他元素",但它不一定是最后一项.请注意,它x
始终是一个列表:
>>> x, *xs = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3, 4]
>>> *xs, x = (1, 2, 3, 4)
>>> xs
[1, 2, 3]
>>> x
4
>>> x, *xs, y = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3]
>>> y
4
>>> for (x, *y, z) in [ (1, 2, 3, 4) ]: print(x, y, z)
...
1 [2, 3] 4
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19860 次 |
最近记录: |