python - 在 Python 2 中将多个列表和字典解包为函数参数

标签 python python-3.x python-2.x

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 分支。
解包列表并传递给 *argsPython 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
解压字典并传递给 **kwargsPython 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/

相关文章:

python - 使用 scrapy python 使用 post 请求加载更多文章

python - 断点续传的 "temp files"算入每月存储费吗? (谷歌云存储)

c++ - 选择索引不连续的 Armadillo 子矩阵

python - 为什么 int(50)<str(5) 在 python 2.x 中?

python - Round Function 在 v2.6.6 中不起作用,但在 v3.4.2 中起作用

python - 接收 pandas DataFrame 中列的 NaN

python - 模拟将 UUID 编码为 Base64

python-3.x - Monkeypatch setenv 值在 python unittest 中跨测试用例持续存在

xml - Python xml 安装不起作用

python - 以 "rock&roll"模式打开文件