首页 > 解决方案 > 映射一个字符串获取每个单词的长度并附加到一个带有条件的新单词

问题描述

我正在尝试添加任何长度大于 5 个字符的单词,但我不知道如何添加这些单词。

s = 'This sentence is a string'
l = list(map(len, s.split()))
l.sort()
w=[]
for i in l:
    if (i >= 5):
        w.append(i)
        print(w)

output [6]
             [6, 8]

我可以得到句子中每个单词的大小,但是将长度与单词本身联系起来很困难,因为它在字符串和整数之间。

标签: pythonpython-3.x

解决方案


您可以简单地使用列表理解来做到这一点:

s = 'This sentence is a string'
words = [w for w in s.split() if len(w) > 5]
print(words) # ==> ['sentence', 'string']

或者,也可以使用afilter和 a :lambda

s = 'This sentence is a string'
words = list(filter(lambda w: len(w) > 5, s.split()))
print(words) # ==> ['sentence', 'string']

推荐阅读