python - 映射一个字符串获取每个单词的长度并附加到一个带有条件的新单词
问题描述
我正在尝试添加任何长度大于 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]
我可以得到句子中每个单词的大小,但是将长度与单词本身联系起来很困难,因为它在字符串和整数之间。
解决方案
您可以简单地使用列表理解来做到这一点:
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']
推荐阅读
- python - python中的正则表达式,替换除了#hashtag和@username之外的所有元音
- google-fit - 如何在 google fit REST API 中获取 Heart points
- c# - 未处理的异常 System.OverflowException 值对于 Int32 来说太大或太小
- javascript - 从 jQuery 自动完成更新敲除绑定输入字段
- java - 哪个 java 与 %JAVA_HOME% 不同
- amazon-dynamodb - 如何以编程方式恢复 DynamoDB 中的备份表?(使用 C#)
- angular - 如何以正确的方式编辑角度材料 filterPredicate?
- sql - 选择查询以将每天的缺失值显示为 0
- mysql - Spring JPA - 准备好的语句查询?
- eclipse - Eclipse SSH 身份验证失败