在函数中返回几个值时出现问题?

时间:2018-11-29 16:06:49

标签: python python-3.x tuples

我要在函数中返回几个值:

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'}

1 个答案:

答案 0 :(得分:5)

使用tuple运算符解压缩函数结果(为*):

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

该语法仅在Python> = 3.5中可用。否则,您可以使用简单的串联:

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