I would like to make a search with some conditions into my list of words.
This is part of my code :
# -*- 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')
My list looks like this :
'cresson', 'crête', 'Créteil', 'crétin', 'creuse', 'creusé', 'creuser',...
I would like to set these conditions :
How I can do that ?
You can do in one list-comprehension:
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']
I found the solution :
# -*- 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.