用内置在map函数中的pythons替换函数

2024-06-16 13:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当前功能(工作)

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的实现(不起作用)

^{pr2}$

如果有人能帮我解决这个问题,我将非常感激。在


Tags: lambda函数字符串in功能map列表len
3条回答

这里有4段代码用于您的逻辑。在

我添加了map而没有lambda,因为这是最有效的,也是一个列表理解的变体,因为很多人认为这是最具Python的。时间安排仅供参考。在

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

def word_lengths_map(phrase):
    return list(map(len, phrase.split(' ')))

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

def word_lengths_lcomp(phrase):
    return [len(x) for x in phrase.split(' ')]

word_lengths(phrase)         # 4.5 microseconds
word_lengths_map(phrase)     # 2.3 microseconds
word_lengths_lambda(phrase)  # 4.0 microseconds
word_lengths_lcomp(phrase)   # 2.8 microseconds
# [3, 4, 3, 3, 5, 2, 4, 6]

{1{创建一个字符的数组}(这将使每个字符的长度^ 1)通过

你应该把整个短语分开:

list(map(len, phrase.split(' ')))

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

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

输出:

^{pr2}$

来自评论:更好的方法。谢谢卢卡斯·格拉夫。在

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

相关问题 更多 >