【问题标题】:How to get the top three elements from a list in Python? (Vowels)如何从 Python 中的列表中获取前三个元素? (元音)
【发布时间】:2021-09-12 13:33:13
【问题描述】:

我目前正在学习 Python 课程(极端菜鸟/初学者级别),但不小心写了一个代码,给出了一个元音最多的国家,而我需要获得元音最多的前三个国家。 这是我目前仅获得一个国家/地区的方式:

def most_vowels(countries):
    vowels = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]
    vowel_list = []
    for country in countries:
        length_vowels = len(set(country).intersection(set(vowels))) 
        vowel_list.append(length_vowels)
    max_vowel = max(vowel_list)
    location_most_vowel = vowel_list.index(max_vowel) 
    country_most_vowel = countries[234]
    return country_most_vowel

我已经阅读了一些关于 n 最大的内容,但我遇到的大多数解决方案还没有在课程中涵盖。 (目前的作业是练习 for 循环)我对我还没有学过的信息很好奇,但我怀疑在不了解基础知识的情况下可以进入。

我可以使用哪些初学者工具/功能/技术?

【问题讨论】:

  • 可以在代码中添加countries 吗?
  • 嗨,如果我说得对,课程从另一个 (json) 文件导入列表并使用“从助手导入 get_countries”(如果这听起来含糊不清,我很抱歉,我很新编程!)
  • 我使用了自己的国家/地区列表并提供了一个简单的解决方案。

标签: python loops element


【解决方案1】:

看看下面(使用我自己的国家/地区列表)

countries = [
    {"name": "Afghanistan", "code": "AF"},
    {"name": "land Islands", "code": "AX"},
    {"name": "Albania", "code": "AL"},
    {"name": "Algeria", "code": "DZ"},
    {"name": "American Samoa", "code": "AS"},
    {"name": "AndorrA", "code": "AD"},
    {"name": "Angola", "code": "AO"},
    {"name": "Anguilla", "code": "AI"},
    {"name": "Antarctica", "code": "AQ"},
    {"name": "Antigua and Barbuda", "code": "AG"},
    {"name": "Argentina", "code": "AR"},
    {"name": "Armenia", "code": "AM"},
    {"name": "Aruba", "code": "AW"},
    {"name": "Australia", "code": "AU"},
    {"name": "Austria", "code": "AT"},
    {"name": "Azerbaijan", "code": "AZ"},
    {"name": "Bahamas", "code": "BS"},
    {"name": "Bahrain", "code": "BH"},
    {"name": "Bangladesh", "code": "BD"},
    {"name": "Barbados", "code": "BB"},
    {"name": "Belarus", "code": "BY"},
    {"name": "Belgium", "code": "BE"},
    {"name": "Belize", "code": "BZ"}
]
result = []
vowels = {"A", "a", "E", "e", "I", "i", "O", "o", "U", "u"}
for country in countries:
    c = country['name']
    cnt = 0
    for x in c:
        if x in vowels:
            cnt += 1
    result.append((c, cnt))
result = sorted(result, key=lambda x: x[1],reverse=True)[:3]
print(result)

输出(前 3 名)

[('Antigua and Barbuda', 8), ('American Samoa', 7), ('Australia', 5)]

【讨论】:

  • 您好,感谢您与我分享您富有洞察力的解决方案。有没有可以在没有 key、lambda 和 reverse 的情况下使用的技术?不幸的是,我还没有了解这些,所以有点难以理解。
  • @Jay 试试看docs.python.org/3/howto/sorting.html#key-functions,希望对你更清楚。
  • 非常感谢!!我会通读一遍,尽我所能。
猜你喜欢
  • 2015-08-06
  • 2016-01-14
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
相关资源
最近更新 更多