我有以下列表:
brand=["Audi","Mercedes"]
speed=[130,150]
model=["sport","family"]
我想获得等价的:
ll=[]
ll.append({'brand':'mercedes', 'speed':130, 'model':'family'})
ll.append({'brand':'mercedes', 'speed':130, 'model':'sport'})
ll.append({'brand':'audi', 'speed':130, 'model':'family'})
ll.append({'brand':'audi', 'speed':130, 'model':'sport'})
ll.append({'brand':'mercedes', 'speed':150, 'model':'family'})
ll.append({'brand':'mercedes', 'speed':150, 'model':'sport'})
ll.append({'brand':'audi', 'speed':150, 'model':'family'})
ll.append({'brand':'audi', 'speed':150, 'model':'sport'})
我现在做:
from itertools import product
ll=list(product(speed, model, brand))
我有所有需要的组合,但这只是列表的列表,而不是字典的列表。我不知道是否有一种直接的蟒蛇式的方法来做到这一点!
用键压缩您的值:
keys = 'brand', 'speed', 'model'
ll = [dict(zip(keys, combo)) for combo in product(brand, speed, model)]
演示:>>> from itertools import product
>>> from pprint import pprint
>>> brand = ["Audi", "Mercedes"]
>>> speed = [130, 150]
>>> model = ["sport", "family"]
>>> keys = 'brand', 'speed', 'model'
>>> [dict(zip(keys, combo)) for combo in product(brand, speed, model)]
[{'speed': 130, 'brand': 'Audi', 'model': 'sport'}, {'speed': 130, 'brand': 'Audi', 'model': 'family'}, {'speed': 150, 'brand': 'Audi', 'model': 'sport'}, {'speed': 150, 'brand': 'Audi', 'model': 'family'}, {'speed': 130, 'brand': 'Mercedes', 'model': 'sport'}, {'speed': 130, 'brand': 'Mercedes', 'model': 'family'}, {'speed': 150, 'brand': 'Mercedes', 'model': 'sport'}, {'speed': 150, 'brand': 'Mercedes', 'model': 'family'}]
>>> pprint(_)
[{'brand': 'Audi', 'model': 'sport', 'speed': 130},
{'brand': 'Audi', 'model': 'family', 'speed': 130},
{'brand': 'Audi', 'model': 'sport', 'speed': 150},
{'brand': 'Audi', 'model': 'family', 'speed': 150},
{'brand': 'Mercedes', 'model': 'sport', 'speed': 130},
{'brand': 'Mercedes', 'model': 'family', 'speed': 130},
{'brand': 'Mercedes', 'model': 'sport', 'speed': 150},
{'brand': 'Mercedes', 'model': 'family', 'speed': 150}]