给字典的笛卡尔积
Posted
技术标签:
【中文标题】给字典的笛卡尔积【英文标题】:Cartesian product giving a dictionary 【发布时间】:2014-08-18 11:35:06 【问题描述】:我有以下列表:
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】:用键压缩你的值:
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]
【讨论】:
以上是关于给字典的笛卡尔积的主要内容,如果未能解决你的问题,请参考以下文章