代码之家  ›  专栏  ›  技术社区  ›  YOU

如何提取要列出的python dict值的每个可能值

  •  1
  • YOU  · 技术社区  · 15 年前
    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"]
    

    附言:秩序无关紧要

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

    2 回复  |  直到 15 年前
        1
  •  4
  •   Alex Martelli    15 年前

    关于以下基本主题的许多可能的次要变体:

    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)
    ]
    
        2
  •  4
  •   sykora    15 年前

    我喜欢和 itertools 我自己,但本质上与亚历克斯的解决方案相同:

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