gpt4 book ai didi

python - 从 Python 3 中的列表填充 map 的单行方法

转载 作者:行者123 更新时间:2023-11-28 17:13:39 24 4
gpt4 key购买 nike

我正在将这段代码从 Python 2.x 移植到 Python 3.x

def funk(arg):
return "%s" % str(arg)

args = map(funk, [1, 2, 3, 4])
args += [5, 6, 7, 8]

Python 3 的最后一行给出了错误

TypeError: unsupported operand type(s) for +=: 'map' and 'list'

如何用一行代码替换最后一行?

最佳答案

map 的返回值在 Python 3 中发生了变化,它现在返回一个值的迭代器,就像 itertools.imap 在 Python 2 中所做的那样。您需要应用 list 到 map 的输出,现在按照 Christian 的建议获取列表。如果您希望您的代码可以跨 Python 2 和 3 移植,您可以使用 six 包导入 map 版本,它返回一个迭代器:from six。移动导入 map

关于python - 从 Python 3 中的列表填充 map 的单行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45641600/

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