简体   繁体   中英

How to get all possible combinations

I've got something dict like that:

{'Y': [1, 2, 6, 7],
 'X': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
 'Z': [0, 3, 6, 9]}

There could be more than 3 variables. I wan't to get all combination of these variables. To get something like:

[{'Y': 1, 'X': 0, 'Z': 0},
 {'Y': 1, 'X': 0, 'Z': 3} ....]

I can't figure algorithm for that. Please help me.

The other posters are right: itertools.product is very helpful here. However, some care will be needed to ensure you get the original dictionary keys, because of the way your dictionary is formatted.

import itertools

data = {'Y': [1, 2, 6, 7],
        'X': [0, 1, 2, 3, 4, 5, 6, 7,
              8, 9, 10, 11, 12, 13, 14, 15, 16,
              17, 18, 19, 20, 21, 22, 23, 24],
        'Z': [0, 3, 6, 9]}
# Join the key and value together in tuples
# [[('Y', 1), ('Y', 2), ('Y', 6), ('Y', 7)], ...]
tuples = [[(var, val) for val in data[var]] for var in data]

# Create the dictionary setting values to X, Y, and Z
# [{'Y': 1, 'X': 0, 'Z': 0}, {'Y': 1, 'X': 0, 'Z': 3} ....]
answer = [dict(a) for a in itertools.product(*tuples)]

Using list(itertools.product(*your_dict.values())) can simply get it :)

EDIT: for your expected result, I've wrote the following:

 [{key: value[n] for n, key in enumerate(your_dict.keys())} for value in itertools.product(*your_dict.values())]

Not that good-looking but it just works (Only in Python 2.7+).

基于Felix Yan的解决方案好看一些:

[dict(zip(your_dict.keys(), item)) for item in itertools.product(*your_dict.values())]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM