Possible Relevant Questions (我搜索了同样的问题,但找不到)
Python 提供了一种使用星号将参数解包为函数的便捷方法,如 https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists 中所述。
>>> 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]
在我的代码中,我正在调用这样的函数:
def func(*args):
for arg in args:
print(arg)
在 Python 3 中,我这样称呼它:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
func(*a, *b, *c)
哪些输出
1 2 3 4 5 6 7 8 9
然而,在 Python 2 中,我遇到了一个异常:
>>> func(*a, *b, *c)
File "<stdin>", line 1
func(*a, *b, *c)
^
SyntaxError: invalid syntax
>>>
似乎 Python 2 无法处理多个列表的解包。有没有比这更好、更干净的方法来做到这一点
func(a[0], a[1], a[2], b[0], b[1], b[2], ...)
我的第一个想法是我可以将列表连接成一个列表并解压缩它,但我想知道是否有更好的解决方案(或我不明白的东西)。
d = a + b + c
func(*d)
最佳答案
建议:迁移到 Python 3
自 2020 年 1 月 1 日起,Python 软件基金会不再支持 Python 编程语言的 2.x 分支。
解包列表并传递给 *args
Python 3 解决方案
def func(*args):
for arg in args:
print(arg)
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
func(*a, *b, *c)
Python 2 解决方案如果需要 Python 2,则
itertools.chain
将提供解决方法:import itertools
def func(*args):
for arg in args:
print(arg)
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
func(*itertools.chain(a, b, c))
输出1
2
3
4
5
6
7
8
9
解压字典并传递给 **kwargs
Python 3 解决方案def func(**args):
for k, v in args.items():
print(f"key: {k}, value: {v}")
a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}
func(**a, **b, **c)
Python 2 解决方案如 Elliot评论中提到,如果您需要解压多个字典并传递给
kwargs
,您可以使用以下内容:import itertools
def func(**args):
for k, v in args.items():
print("key: {0}, value: {1}".format(k, v))
a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}
func(**dict(itertools.chain(a.items(), b.items(), c.items())))
关于python - 在 Python 2 中将多个列表和字典解包为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000998/