![](/img/trans.png)
[英]How do I check if a string contains ALL letters of the alphabet in python?
[英]How do I extract a maximum of 14 names out of a big list that, together, have all the letters of the alphabet?
我是一名新程序員。 正如標題所述,這是我完成此任務的嘗試:
def alphabet_set(countrylist):
alphabetical_list = []
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for country in countries:
for i in country:
if i in alphabet:
alphabetical_list.append(country)
if i == 26:
break
return alphabetical_list
print(alphabet_set(countries))
同樣,我從中提取的這個列表很大。 我需要 14 個國家/地區名稱,這將給我字母表的所有字母。 Alphabetical_list 將是我的 14 個國家/地區列表,其中包含所有 26 個字母表中的字母。
你可以使用set()
def alphabet_set(countrylist:list[str]):
alphabetical_list = []
alphabet = 'abcdefghijklmnopqrstuvwxyz'
countriescontains = []
letters = set()
for country in countrylist:
if len(letters)==26 or len(alphabetical_list) == 14:break
elif set(country.lower()).intersection(alphabet):
alphabetical_list.append(country)
print({x.lower() for x in country},letters.union({x.lower() for x in country}))
letters=letters.union({x.lower() for x in country if x != ' '})
print(sorted(list(letters)))
return alphabetical_list
print(alphabet_set(countries))
這會將alphabet_set
的復雜性從O(n^2)
降低到O(n)
,這將是性能方面的巨大改進。
好的,這是我想出的答案:
def alphabet_set(countries):
alphabetical_list = []
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for country in countries:
for i in country:
if i.lower() in alphabet and country not in alphabetical_list:
alphabet = alphabet.replace(i.lower(),'')
alphabetical_list.append(country)
if alphabet == '':
break
return alphabetical_list
print(alphabet_set(countries))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.