Skip to main content
 首页 » 编程设计

python之在函数中返回多个值时出现问题

2025年05月04日22jiqing9006

我在一个函数中返回了几个值:

def count_chars(e): 
    return len(e), 'bar' 

像这样:

for d in lst: 
    newlst = [] 
    for x in d["data"]: 
        newlst.extend([x, count_chars(x)]) 
        d["data"] = newlst 
pprint(lst) 

但是,当我返回元组中的值时:

{'data': ['YES', (9, 'bar')], 'info': 'AKP'} 

我怎样才能摆脱元组?对于

{'data': ['YES', 9, 'bar'], 'info': 'AKP'} 

请您参考如下方法:

使用* 运算符解压函数结果(它是一个元组):

newlst.extend([x, *count_chars(x)]) 

该语法仅在 Python >= 3.5 中可用。否则你可以使用简单的连接:

newlst.extend([x] + list(count_chars(x)))