对象列表中列表的列表理解
List comprehension of lists inside a list of objects
假设我有以下数据结构:
SOME_LIST = [
{
'name': 'foo',
'alternatives': [
{
'name': 'Foo'
},
{
'name': 'foo'
},
{
'name': 'fu
}
]
},
{
'name': 'bar',
'alternatives': [
{
'name': 'Bar'
},
{
'name': 'bar'
},
{
'name': 'ba'
}
]
}
]
我想生成对象的备选“名称”的扁平化列表,如下所示:
['foo', 'Foo', 'fu', ..., 'ba']
我已经用各种列表理解遍历了所有房子...但我只是不知道如何优雅地做到这一点。
我试过:
[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
您可以使用嵌套列表理解:
result = [j['name'] for i in SOME_LIST for j in i['alternatives']]
输出:
['Foo', 'foo', 'fu', 'Bar', 'bar', 'ba']
假设我有以下数据结构:
SOME_LIST = [
{
'name': 'foo',
'alternatives': [
{
'name': 'Foo'
},
{
'name': 'foo'
},
{
'name': 'fu
}
]
},
{
'name': 'bar',
'alternatives': [
{
'name': 'Bar'
},
{
'name': 'bar'
},
{
'name': 'ba'
}
]
}
]
我想生成对象的备选“名称”的扁平化列表,如下所示:
['foo', 'Foo', 'fu', ..., 'ba']
我已经用各种列表理解遍历了所有房子...但我只是不知道如何优雅地做到这一点。
我试过:
[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
您可以使用嵌套列表理解:
result = [j['name'] for i in SOME_LIST for j in i['alternatives']]
输出:
['Foo', 'foo', 'fu', 'Bar', 'bar', 'ba']