gpt4 book ai didi

python - 计算列表中的初学者单词 : Python

转载 作者:太空狗 更新时间:2023-10-30 01:45:05 24 4
gpt4 key购买 nike

正在处理一个非常常见的问题,以确定单词是否为初学者(所有字母均按字母顺序排列)。正如在“Think Python”中发现的那样,我可以用多种方式来表达一个词;但是,希望能够遍历一个单词列表,确定哪些是初学者,并计算那些是初学者的单词。

def start():
lines= []
words= []
for line in open('word_test1.txt'):
lines.append(line.strip())
numlines=len(lines)
count = 0

for word in lines[:]:
i = 0
while i < len(word)-1:
if word[i+1] < word[i]:
return
i = i+1
print (word)
count= count + 1
print (count)
start()

我认为我的问题在于“while i”循环中的“return”。在我使用的列表中,至少有三个初级单词。上面的代码读取前两个(第一个条目),打印它们,对它们进行计数,但在接下来的非初学者单词上跳出循环并结束程序。

我是编程新手,这几天花了我好几个小时。

最佳答案

无需对此进行低级编程:-)

def is_abcedarian(s):
'Determine whether the characters are in alphabetical order'
return list(s) == sorted(s)

用途filter遍历单词列表:

>>> filter(is_abcedarian, ['apple', 'bee', 'amp', 'sun'])
['bee', 'amp']

关于python - 计算列表中的初学者单词 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9967395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com