如何提取python Dict的值的每个可能值列表

时间:2009-12-07 04:30:10

标签: python

DICTA={'bw':['BW','VW'],'b':['BB','VV'],'a':['AA']}
DICTB={'yn':['$YN','$YNN'],'ye':['$YE','A$Y'],'y':['Y$']}

如何将该2 Dict的每个可能值提取到

["BWYN","VWYN","BBYN","VVYN","AAYN","BWYNN","VWYNN","BBYNN","VVYNN","AAYNN",
"BWYE","VWYE","BBYE","VVYE","AAYE","ABWY","AVWY","ABBY","AVVY","AAAY",
"YBW","YVW","YBB","YVV","YAA"]

PS:订单无关紧要

PPS:不是家庭作业,而是想知道如何以有效的方式实施。

2 个答案:

答案 0 :(得分:4)

以下基本主题的许多可能的小变体:

print [y.replace('$', x)
  for y in (v for y in DICTB.values() for v in y)
  for x in (v for y in DICTA.values() for v in y)
]

答案 1 :(得分:4)

我喜欢自己选择itertools,但与Alex的解决方案基本相同:

from itertools import product

[
    y.replace('$', x)
    for (x, y) in product(sum(DICTA.values(), []), sum(DICTB.values(), []))
]