mydict ={1:'All',
 2:'Web',
 4:'Iphone',
 8:'Ipad', 
 16:'Android',
 32:'Iphone-Web',
 64:'Ipad-Web',
 128:'Android-Web',
 256:'Android-Web-Desktop',
 512:'Iphone-Web-Desktop',
 1024:'Ipad-Web-Desktop'}

This is my dictionary. How to print all possible combinations like:

 1:'All'
 2:'Web'
 4:'Iphone'
 8:'Ipad'
 16:'Android'
 32:'Iphone-Web'
64:'Ipad-Web'
128:'Android-Web'
256:'Android-Web-Desktop'
512:'Iphone-Web-Desktop'
1024:'Ipad-Web-Desktop'
3:'All-Web'
5: 'All-Iphone'
6: 'Web-Iphone'
7: 'All-Web-Iphone'

and so on. The combination needs to be created using this idea,

sum(keys): 'values(key1)-value(key2)'

.Also there are few combinations already, please assume them as new device. The maximum length of combinations is len(mydict). I need it in Python. Thanks.

有帮助吗?

解决方案

Printing all single result and then combinations of two keys using combinations.

from itertools import combinations

for key in mydict:
    print "{}: '{}'".format(key, mydict[key])

for x, y in combinations(mydict, 2):
    print "{}: '{}'".format(x+y, '-'.join((mydict[x], mydict[y])))

UPDATED

Print all possible combinations.

from itertools import combinations

for n in range(len(mydict)):
    for combs in combinations(sorted(mydict), n+1):
        print "{}: '{}'".format(sum(combs), '-'.join([mydict[key] for key in combs]))

其他提示

We don't know what you are actually looking for, but if it it is the powerset you are looking for:

from copy import deepcopy
def powerset (id_base=0, prefix="", dictionary=dict(), length=0):
    if length < 0:
        return dict()
    if length == 0:
        return dict((id_base,prefix))
    if len(prefix):
        prefix = prefix + "-"
    this_powerset = dict()
    for key, item in dictionary.items():
        smaller_dictionary = deepcopy(dictionary)
        del smaller_dictionary[key]
        this_powerset = dict(
            powerset( id_base + key,
                      prefix + item,
                      smaller_dictionary,
                      length - 1 ).items()
            + this_powerset.items()
    return this_powerset

run as

the_set = powerset(dictionary = mydict, length = len(mydict))

(Comes with all the exectution time problems of recursive functions)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top