[英]How to find words in a list that contain the same first letter python
編寫一個函數common_start(word_list)
,它接受一個單詞列表作為參數。 此函數必須返回一個新列表,其中包含以與列表中至少一個其他單詞相同的字母開頭的所有單詞。
輸入:['文件','編輯','查看','插入','格式']
輸出:['文件','格式']
一個單行解決方案,如果你想
def common_start(input_list):
return [word for word in input_list if sum([w.startswith(word[0]) for w in input_list]) > 1]
這應該對你有用。 在這種情況下,我忽略了重復的單詞。
def common_start(word_list):
output = set()
for word in word_list:
for first_letter in word_list:
if word == first_letter:
next
elif word[0] == first_letter[0]:
output.add(word)
return list(output)
輸入:['tara', 'file', 'edit', 'view', 'insert', 'format','test']
輸出:['tara', 'file', 'format', 'test']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.