python:迭代包含列表作为值的字典的每个组合

python:迭代包含列表作为值的字典的每个组合,python,python-2.7,Python,Python 2.7,假设我有一本字典,它是dictList={1:[1,3,4,8],2:[5,7,2,8],3:[6,3,5,7]} 我想打印所有组合,如下所示: 键、值 第一次迭代 1,1 2,5 3,6 第二次迭代 1,1 2,5 3,3 .... 以此类推假设您要做的是检索每一组唯一的三个键、值对: from itertools import permutations # define dictList # define numkeys to be the number of keys in dictLi

假设我有一本字典,它是dictList={1:[1,3,4,8],2:[5,7,2,8],3:[6,3,5,7]}

我想打印所有组合,如下所示: 键、值 第一次迭代 1,1 2,5 3,6 第二次迭代 1,1 2,5 3,3
.... 以此类推

假设您要做的是检索每一组唯一的三个键、值对:

from itertools import permutations
# define dictList
# define numkeys to be the number of keys in dictList
# define maxLen to be the number of items in each dict value
perms = permutations(range(maxLen),numKeys)
for p in perms:
    i = 1     # you're indexing your dictionary from 1, not 0
    while i <= numKeys:
        myfunction(i,dictList[i][p[i-1]])   # ...which is why this is awkward
        i += 1
从itertools导入置换
#定义听写列表
#将numkeys定义为dictList中的键数
#将maxLen定义为每个dict值中的项数
置换=置换(范围(最大值),numKeys)
对于烫发中的p:
i=1#您正在从1而不是0为词典编制索引

虽然我像别人说的那样,但你似乎错误地解释了你的问题。 但我想你想要的是:

[(1,1)、(2,5)、(3,6)、(1,3)、(2,7)、(3,3)、(1,4)、(2,2)、(3,5)、(1,8)、(2,8)、(3,7)]

我将尝试使用
zip
。例如,值上的zip将关联所有第一项、所有第二项等

警告:只有当列表长度相同时才有效!!! (否则您可以导入
itertools.izip\u longest
来替换zip,额外的索引将返回None)

因此,以下代码:

for t in zip(*dictList.values()):
...    for i, k in enumerate(dictList.keys()):
...       print k, t[i]
将打印:

1 1
2 5
3 6
1 3
2 7
3 3
1 4
2 2
3 5
1 8
2 8
3 7
有一种方法可以在一行中完成:

>>> reduce(lambda cumul, v:cumul + list(zip(dictList.keys(), v)), zip(*dictList.values()), [])
[(1, 1), (2, 5), (3, 6), (1, 3), (2, 7), (3, 3), (1, 4), (2, 2), (3, 5), (1, 8), (2, 8), (3, 7)]
是的,我知道,它不是真正可读的,但我发现尝试在一行xD中做这种事情很有趣 在使用它之前,花点时间了解正在发生的事情

希望有帮助,
祝您有愉快的一天。

第二次迭代是指1,3 2,7 3,3吗?您想要打印的帽子的图案是什么。正确地解释你的问题。不要仅仅因为一个男人没有正确地表达他的问题就对他指手画脚。这件事发生在我们所有人身上,这不是懒惰@阿布杜拉:我没有得到你想要的组合,请提供更多细节,并检查你是否犯了错误。请编辑你的问题以解释你真正想要的…这将根据OP的列表生成索引器。不,我没有运行它,但我只是假设它会运行,因为您没有定义
max
anywhere:)我的英语很烂,我以前的评论应该用不同的措辞。我说“假设您知道字典中的每个列表都有长度
max
”这意味着您将
max
设置为列表的长度。是的,我太草率了,对不起!:)我很抱歉。我试图正确地解释这些组合。但是stackoverflow限制了我去了解更多细节。实际上,这些组合是:这个解决方案很巧妙,但我认为这不是OP想要的;相反,需要所有可能的值的组合。对不起,你回答了。谢谢
    from itertools import product
    from itertools import izip_longest  # This is used to deal with variable length of lists

    dictList = {1:[1,3,4,8], 2:[5,7,2,8], 3:[6,3,5,7,8]}

    dict1 = [dict(izip_longest(dictList, v)) for v in product(*dictList.values())]

    for dict2 in dict1:
        for key, value in dict2.items():
            print key, value
    from itertools import product
    from itertools import izip_longest  # This is used to deal with variable length of lists

    dictList = {1:[1,3,4,8], 2:[5,7,2,8], 3:[6,3,5,7,8]}

    dict1 = [dict(izip_longest(dictList, v)) for v in product(*dictList.values())]

    for dict2 in dict1:
        for key, value in dict2.items():
            print key, value