【问题标题】:Is there a way to iterate through a sublist and return a particular value?有没有办法遍历子列表并返回特定值?
【发布时间】:2021-04-07 02:58:19
【问题描述】:

我有以下字典,其中包含嵌套字典:

rarebirds = {
    'Gold-crested Toucan': {
        'Height (m)': 1.1,
        'Weight (kg)': 35,
        'Color': 'Gold',
        'Endangered': True,
        'Aggressive': True},
    'Pearlescent Kingfisher': {
        'Height (m)': 0.25,
        'Weight (kg)' : 0.5,
        'Color': 'White',
        'Endangered': False,
        'Aggressive': False},
    'Four-metre Hummingbird': {
        'Height (m)': 0.6,
        'Weight (kg)': 0.5,
        'Color' : 'Blue',
        'Endangered' : True,
        'Aggressive' : False},
    'Giant Eagle': {
        'Height (m)' : 1.5,
        'Weight (kg)' : 52,
        'Color' : 'Black and White',
        'Endangered' : True,
        'Aggressive' : True},
    'Ancient Vulture': {
        'Height (m)' : 2.1,
        'Weight (kg)' : 70,
        'Color' : 'Brown',
        'Endangered' : False,
        'Aggressive': False}
}

如果此列表中的一只鸟确实具有攻击性,我应该打印出一份声明,上面写着“Cover your head”。我不知道如何让 Python 遍历列表的每个元素并仅在鸟具有攻击性的情况下打印某些内容。请指教。

【问题讨论】:

    标签: nested-for-loop


    【解决方案1】:

    试试这个,它遍历字典值:

    rarebirds = {...}
    for bird_dict in rarebirds.values():
        if bird_dict["aggressive"]:
            print("Cover your head!")
    

    或者,您可以遍历字典的键:

    rarebirds = {...}
    for bird in rarebirds:
        if rarebirds[bird]["aggressive"]:
            print("Cover your head!")
    

    任何一种方式都有效;这主要取决于您的喜好。

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2019-10-14
    • 2021-04-05
    • 2020-06-18
    • 2010-10-06
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多