How to get all mappings between two lists?

后端 未结 2 1073
借酒劲吻你
借酒劲吻你 2021-01-01 13:36

We have two lists, A and B:

A = [\'a\',\'b\',\'c\']
B = [1, 2]

Is there a pythonic way to build the set of all maps between A and B contain

2条回答
  •  余生分开走
    2021-01-01 14:25

    import itertools as it
    
    A = ['a','b','c']
    B = [1, 2]
    
    for i in it.product(*([B]*len(A))):
        print(list(zip(A, i)))
    

    outputs:

    [('a', 1), ('b', 1), ('c', 1)]
    [('a', 1), ('b', 1), ('c', 2)]
    [('a', 1), ('b', 2), ('c', 1)]
    [('a', 1), ('b', 2), ('c', 2)]
    [('a', 2), ('b', 1), ('c', 1)]
    [('a', 2), ('b', 1), ('c', 2)]
    [('a', 2), ('b', 2), ('c', 1)]
    [('a', 2), ('b', 2), ('c', 2)]
    

    Not sure if it's very pythonic, it is if you look at it.product(*([B]*len(A))), because it uses multiple python-specific language features. But it's actually too cryptic to be pythonic... B is repeated n-times based on length of A and unpacked to the product-function.

提交回复
热议问题