Я хотел бы сделать поиск с некоторыми условиями в моем списке слов.
Это часть моего кода:
# -*- 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",...
Я хотел бы установить следующие условия:
Как я могу это сделать?
Вы можете сделать это в одном понимании списка:
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']
Предполагая нечувствительность к регистру и у вас есть доступ к f-строкам (Python 3.6):
[s for s in content if len(s) == 9 and f'{s[0]}{s[-1]}'.lower() == 'ce']
Я нашел решение:
# -*- 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)