如何使用列表推导从另一个列表中获取一些数据? [英] How can I use list comprehension to get some data from another list?

查看:58
本文介绍了如何使用列表推导从另一个列表中获取一些数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有以下列表:

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

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

and I would like to build the following list (using list comprehensions):

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

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

I tried these without success:

[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']]

推荐答案

如果要使用双循环:

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

您必须:

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

如果您dict x具有多个值,则可以使用

If you dict x, has multiple values, you can use

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

这篇关于如何使用列表推导从另一个列表中获取一些数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆