[英]List comprehension of lists inside a list of objects
Let's say I have the following data structure:假设我有以下数据结构:
SOME_LIST = [
{
'name': 'foo',
'alternatives': [
{
'name': 'Foo'
},
{
'name': 'foo'
},
{
'name': 'fu
}
]
},
{
'name': 'bar',
'alternatives': [
{
'name': 'Bar'
},
{
'name': 'bar'
},
{
'name': 'ba'
}
]
}
]
I want to produce a flattened list of the alternative "names" of the object as follows:我想生成 object 的替代“名称”的扁平列表,如下所示:
['foo', 'Foo', 'fu', ..., 'ba']
I've gone around the houses with various list comprehensions...and I just don't know how to do this elegantly.我已经用各种列表理解绕着房子走来走去......我只是不知道如何优雅地做到这一点。
I've tried:我试过了:
[i['alternatives'] for i in SOME_LIST]
[*i['alternatives'] for i in SOME_LIST]
>>>SyntaxError: iterable unpacking cannot be used in comprehension
[alt['name'] for alt in [i['alternatives'] for i in SOME_LIST]]
>>>TypeError: list indices must be integers or slices, not str
You can use a nested list comprehension:您可以使用嵌套列表推导:
result = [j['name'] for i in SOME_LIST for j in i['alternatives']]
Output: Output:
['Foo', 'foo', 'fu', 'Bar', 'bar', 'ba']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.