我想在某些条件下搜索我的单词列表。
这是我的代码的一部分:
# -*- coding: utf-8 -*-
with open(r"C:\Users\Valentin\Desktop\list.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
all_words = ','.join(content)
end = all_words.endswith('e')
我的列表如下:
'cresson','crête','Créteil','crétin','creuse','creusé', 'creuser',...
我想设置以下条件:
我该怎么做?
答案 0 :(得分:2)
您可以进行一项列表理解:
content = ['cresson', 'crête', 'Créteil', 'crétin', 'creuse', 'creusé', 'creuser']
result = [x for x in content if len(x) == 9 and x.startswith() == 'c' and x.endswith() == 'e']
答案 1 :(得分:2)
假设不区分大小写,并且您可以访问f字符串(Python 3.6):
[s for s in content if len(s) == 9 and f'{s[0]}{s[-1]}'.lower() == 'ce']
答案 2 :(得分:0)
我找到了解决方法:
# -*- coding: utf-8 -*-
with open(r"C:\Users\Valentin\Desktop\list.txt") as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
#print(content)
result = [i for i in content if i.startswith('c')]
result2 = [i for i in result if i.endswith('e')]
result3 = [i for i in result2 if len(i)==9]
print(result3)