gpt4 book ai didi

python - 用 pythons 内置的 map 函数替换函数

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

问题:我想提高我对python map函数的理解。我做了一个函数,它可以将给定短语中单词的长度作为列表返回。但是,我想简单地使用带有 lambda 函数的 map 函数并传入一个字符串。另外,我正在使用 python 3。

当前函数(WORKS):

phrase = 'How long are the words in this phrase'

def word_lengths(phrase):
phrase = phrase.split(' ')
wordLengthList = []
for i in range(len(phrase)):
wordLengthList.append(len(phrase[i]))
return wordLengthList

word_lengths(phrase)

map 的当前实现(不起作用):

 list(map(lambda x: len(x.split(' ')), phrase))

如果有人能帮我解决这个问题,我将不胜感激。

最佳答案

您需要拆分短语变量的输入参数。

print(list(map(lambda x: len(x), phrase.split(" "))))

输出:

[3, 4, 3, 3, 5, 2, 4, 6]

来自评论:更好的方法。谢谢 Lukas Graf。

print(list(map(len, phrase.split(" ")))

关于python - 用 pythons 内置的 map 函数替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623671/

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