首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何从一个大列表中最多提取14个名字,这些名字加在一起,所有的字母都在一起?

我如何从一个大列表中最多提取14个名字,这些名字加在一起,所有的字母都在一起?
EN

Stack Overflow用户
提问于 2022-01-26 15:55:04
回答 2查看 114关注 0票数 0

我是个新程序员。正如标题所述,这是我试图完成的:

代码语言:javascript
复制
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个字母。

EN

回答 2

Stack Overflow用户

发布于 2022-01-26 16:08:04

你可以用set()

代码语言:javascript
复制
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_setO(n^2)O(n)的复杂性,这将大大提高性能。

票数 0
EN

Stack Overflow用户

发布于 2022-03-21 15:28:51

好的,这就是我想出的答案:

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70866353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档