我试图添加任何长度超过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]
我可以得到句子中每个单词的大小,但是将长度与单词本身联系起来很困难,因为它在字符串和整数之间。
你可以简单地使用list-comprehension来做到这一点:
s = 'This sentence is a string'
words = [w for w in s.split() if len(w) > 5]
print(words) # ==> ['sentence', 'string']
或者,也可以使用带有filter
的lambda
:
s = 'This sentence is a string'
words = list(filter(lambda w: len(w) > 5, s.split()))
print(words) # ==> ['sentence', 'string']