猿问

如何使用列表理解从另一个列表中获取一些数据?

您好,我有以下清单:


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


慕工程0101907
浏览 145回答 4
4回答

白衣染霜花

如果要使用双循环:[x['cat'] for y in a for x in y['id'] if type(x) is  dict]你必须 :将 a 列表中的值作为列表获取(对于 a 中的 y)获取 y 中的 'id'(对于 x in y['id'])通过过滤字典跳过字符串“吃”(如果类型(x)是字典)访问“猫”如果你 dict x, 有多个值,你可以使用[x.values() for y in a for x in y['id'] if type(x) is  dict]]

30秒到达战场

您可以使用内置函数itemgetter和 chain(来自 itertools 模块)from itertools import chainfrom operator import itemgetterlist(map(itemgetter('cat'), chain(*map(itemgetter('id'), a))))输出:['billy', 'bill', 'Harry', 'Hary']或者您可以使用for内部有 2 个循环的列表推导,第一个迭代列表中的所有dict元素,第二个迭代最里面的列表并从键“cat”中获取元素:[i['cat'] for d in a for i in d['id']]

神不在的星期二

您可以为此使用以下列表理解:>>> 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']

慕尼黑5688855

你要b = [x['id'][0]['cat'] for x in a]的每个元素a都是一个看起来像{    'Hello': ...,    'id': [        {            'cat': ...        },        ...    ]}
随时随地看视频慕课网APP

相关分类

Python
我要回答