python - 如何使用for循环或while循环根据条件在字符串中查找单词
问题描述
我第一次用字符串练习循环,我想知道是否有一种方法可以编写此代码但指令较少。
count = 0
str = "flying one plane from one place to the other" \
" but one place is a bit small so we will take one more"
for word in str.split():
if (word=='one'):
count+=1
print(count)
for word in str.split():
if (len(word) == 1):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 2):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 3):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 4):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 5):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 6):
print(word, end=" ")
print()
for word in str.split():
if (len(word) == 7):
print(word, end=" ")
print()
输出可以是列表或字符串。我没关系。但必须有一种更清洁的方式来写这个对吗?
解决方案
一种使用方式collections.defaultdict
:
from collections import defaultdict
d = defaultdict(list)
for word in s.split():
d[len(word)].append(word)
for n in sorted(d):
print(*d[n])
输出:
a
to is so we
one one the but one bit one
from will take more
plane place other place small
flying
推荐阅读
- android - TextWatcher 在 DialogFragment 中不起作用
- postgresql - 在 Postgresql 中为列创建行
- c - 即使是 300 个字符输入,代码也无法正确运行
- swift - startTurnByTurnNavigation 最大值 viaWaypoints
- bash - 列出特定路径的目录作为 bash 脚本的自动完成选项?
- fluent - 在fluentd中如何解析日志并根据键值创建字段
- python-3.x - 将结果保存到 csv 文件:TypeError: writerows() 参数必须是可迭代的
- java - 如何在 Java 中对字节数组中的补充 unicode 字符进行编码?
- java - TurboFilter 用于限制记录的异常 - 不起作用
- xamarin - Xamarin / Visual Studio 在 Xamarin.Android 中选择核心库而不是特定平台库