簡體   English   中英

Python:從列表中獲取所有開頭為,開頭為和長度為

[英]Python : Get all occurences from list with startswith, endswith and lenght

我想在某些條件下搜索我的單詞列表。

這是我的代碼的一部分:

# -*- 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',...

我想設置以下條件:

  • 以字母C開頭
  • 以字母'E'結尾
  • 長度:9個字符

我該怎么做?

您可以進行一種列表理解:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM