映射字符串获取每个单词的长度并附加到具有条件的new

问题描述 投票:-1回答:1

我试图添加任何长度超过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]

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

python python-3.x
1个回答
1
投票

你可以简单地使用list-comprehension来做到这一点:

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

或者,也可以使用带有filterlambda

s = 'This sentence is a string'
words = list(filter(lambda w: len(w) > 5, s.split()))
print(words) # ==> ['sentence', 'string']
© www.soinside.com 2019 - 2024. All rights reserved.