gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:10 25 4
gpt4 key购买 nike

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

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

关于python - 在函数中返回多个值时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com