簡體   English   中英

在 Python 2 中將多個列表和字典解包為函數參數

[英]Unpacking multiple lists and dictionaries as function arguments in Python 2

可能的相關問題(我搜索了相同的問題,但沒有找到)


https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists 中所述,Python 提供了一種使用星號將參數解包為函數的便捷方法

>>> 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())))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM