What does *tuple and **dict means in Python?
本问题已经有最佳答案,请猛点这里访问。
在上述pythoncookbook as,before a can be added
和1.18。名称映射到序列的元素:P></
1 2 3 4 | 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) |
在相同截面,
1 2 3 4 5 6 7 | 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) |
什么是S函数
在函数调用中
1 2 3 4 5 6 | def foo(x, y): print(x, y) >>> t = (1, 2) >>> foo(*t) 1 2 |
由于v3.5,您还可以在列表/元组/集合文本中执行此操作:
1 2 | >>> [1, *(2, 3), 4] [1, 2, 3, 4] |
1 2 3 4 5 6 | def foo(x, y): print(x, y) >>> d = {'x':1, 'y':2} >>> foo(**d) 1 2 |
由于v3.5,您还可以在字典文本中执行此操作:
1 2 3 | >>> d = {'a': 1} >>> {'b': 2, **d} {'b': 2, 'a': 1} |
在函数签名中
1 2 3 4 5 | def foo(*t): print(t) >>> foo(1, 2) (1, 2) |
1 2 3 4 5 | def foo(**d): print(d) >>> foo(x=1, y=2) {'y': 2, 'x': 1} |
在赋值和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | >>> 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 |