笛卡儿产品给词典

时间:2014-08-18 11:35:07

标签: python dictionary itertools

我有以下列表:

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

我有所有需要的组合,但这只是列表而不是字典列表。我不知道是否有直接和pythonic的方式来做它!

1 个答案:

答案 0 :(得分:9)

使用键来压缩您的值:

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