问题
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 :
- Get values in the a list as a list (for y in a)
- get the 'id' in y (for x in y['id'])
- Skip the string 'eat' by filtering for dictionary (if type(x) is dict)
- 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