【问题标题】:How can I use list comprehension to get some data from another list?如何使用列表理解从另一个列表中获取一些数据?
【发布时间】:2020-01-29 16:04:23
【问题描述】:

您好,我有以下清单:

a = [{'Hello':5, 'id':[{'cat':'billy', 'dog': 'Paul'}, {'cat':'bill', 'dog': 'Pau'}]},
     {'Hello':1, 'id':[{'cat':'Harry', 'dog': 'Peter'}, {'cat':'Hary', 'dog': 'Pete'}]}]

我想构建以下列表(使用列表推导):

b = ['billy', 'bill', 'Hary', 'Harry']

我尝试了这些但没有成功:

[x for y in a for b in y['id'] for x in b]
[x for y in a for b in y['id'] for x in b['cat']]

【问题讨论】:

  • 您具体在哪个部分苦苦挣扎?

标签: python list dictionary list-comprehension


【解决方案1】:

如果你想使用双循环:

[x['cat'] for y in a for x in y['id'] if type(x) is  dict]

你必须:

  1. 将 a 列表中的值作为列表获取(对于 a 中的 y)
  2. 获取 y 中的 'id'(对于 x in y['id'])
  3. 通过过滤字典跳过字符串“eat”(如果 type(x) 是 dict)
  4. 访问“猫”

如果你dict x,有多个值,你可以使用

[x.values() for y in a for x in y['id'] if type(x) is  dict]]

【讨论】:

  • 谢谢,但我忘记了钥匙狗……现在它不起作用了:/你能帮帮我吗? :)
  • 你可以使用 x.values ,这会给你返回 dict_values
  • 为什么 OP 想要使用“双”(嵌套)循环,而单循环解决方案可用(并且更具可读性)?
  • 为了可读性,我发现很难找出 d['id'][0]['cat'] @DeepSpace 中发生了什么
  • 其实我在我的列表中做错了。这里是正确的。请问你能帮帮我吗 ? :) 非常感谢!
【解决方案2】:

你想要

b = [x['id'][0]['cat'] for x in a]

a 的每个元素都是一个看起来像的字典

{
    'Hello': ...,
    'id': [
        {
            'cat': ...
        },
        ...
    ]
}

【讨论】:

  • 谢谢,但我忘记了钥匙狗……现在它不起作用了:/你能帮帮我吗? :)
  • 我的解决方案不假定 cat 是该字典中的唯一键; dog 的存在与否应该没有区别。
  • 其实我在我的列表中做错了。这里是正确的。请问你能帮帮我吗 ? :) 非常感谢!
【解决方案3】:

您可以为此使用以下列表理解:

>>> a = [{'Hello':5, 'id':[{'cat':'billy', 'dog': 'Paul'}, {'cat':'bill', 'dog': 'Pau'}]},
     {'Hello':1, 'id':[{'cat':'Harry', 'dog': 'Peter'}, {'cat':'Hary', 'dog': 'Pete'}]}]

>>> [y['cat'] for x in a for y in x['id']]
['billy', 'bill', 'Harry', 'Hary']

【讨论】:

    【解决方案4】:

    您可以使用内置函数 itemgetter 和 chain(来自 itertools 模块)

    from itertools import chain
    from operator import itemgetter
    
    list(map(itemgetter('cat'), chain(*map(itemgetter('id'), a))))
    

    输出:

    ['billy', 'bill', 'Harry', 'Hary']
    

    或者你可以使用一个包含 2 个 for 循环的列表推导,首先迭代列表中的所有 dict 元素,然后迭代最里面的列表并从键“cat”中获取元素:

    [i['cat'] for d in a for i in d['id']]
    

    【讨论】:

      猜你喜欢
      • 2011-10-04
      • 1970-01-01
      • 2011-10-13
      • 2021-08-17
      • 2021-10-19
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      相关资源
      最近更新 更多