How can I use list comprehension to get some data from another list?

有些话、适合烂在心里 提交于 2020-01-30 10:49:43

问题


Hello I have the following list :

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

回答1:


If you want to use a double loop:

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

you have to :

  1. Get values in the a list as a list (for y in a)
  2. get the 'id' in y (for x in y['id'])
  3. Skip the string 'eat' by filtering for dictionary (if type(x) is dict)
  4. Access the 'cat'

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



回答2:


You want

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

Each element of a is a dict that looks like

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



回答3:


You can use the following list-comprehension for this:

>>> 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:


you can use build-in functions itemgetter and chain (from itertools module)

from itertools import chain
from operator import itemgetter

list(map(itemgetter('cat'), chain(*map(itemgetter('id'), a))))

output:

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

or you can use a list comprehension with 2 for loops inside, first to iterate over all the dict elements in the list and the second to iterate the innermost lists and grab the element from the key 'cat':

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


来源:https://stackoverflow.com/questions/59971046/how-can-i-use-list-comprehension-to-get-some-data-from-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!