文档中常提到的用法是接受不定数量的参数, 最近发现除此之外, * 用来解包list或dict或set真是好用
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
>>> print(*[1], *[2], 3)
1 2 3
>>> dict(**{'x': 1}, y=2, **{'z': 3})
{'x': 1, 'y': 2, 'z': 3}
>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {*range(4), 4}
{0, 1, 2, 3, 4}
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
>>> {'x': 1, **{'x': 2}}
{'x': 2}
>>> {**{'x': 2}, 'x': 1}
{'x': 1}
#unambiguous and well-defined way:
combination = {**first_dictionary, "x": 1, "y": 2}
#instead of:
combination = first_dictionary.copy()
combination.update({"x": 1, "y": 2})
之前生成一个连续整数的列表,要用列表解析:
foo = [i for i in range(10)]
其实可以不用for语句, 直接这样写:
foo = [*range(10)]
对于分行打印也是如此, 之前这样:
foo = ['a', 'b', 'c', 'd', 'e', 'f']
for i in foo:
print(i)
其实可以这样写:
foo = ['a', 'b', 'c', 'd', 'e', 'f']
print(*foo, sep='\n')