首页 > 解决方案 > 如何使用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()

输出可以是列表或字符串。我没关系。但必须有一种更清洁的方式来写这个对吗?

标签: pythonpython-3.x

解决方案


一种使用方式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

推荐阅读