Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以特定的方式迭代字典?_Python_Loops_Dictionary_Iterator_Iteration - Fatal编程技术网

Python 如何以特定的方式迭代字典?

Python 如何以特定的方式迭代字典?,python,loops,dictionary,iterator,iteration,Python,Loops,Dictionary,Iterator,Iteration,我正试图以一种特定的方式对字典进行迭代。 假设我的字典是这样的: d={'MERRY': [12996, 13225, 18225, 20449, 24336, 27556, 27889, 34225, 46225, 52441, 61009, 62001, 63001, 64009, 70225, 73441, 81225], 'XMAS': [1024, 1089, 1296, 1369, 1764, 1849, 1936, 2304, 2401, 2601,

我正试图以一种特定的方式对字典进行迭代。 假设我的字典是这样的:

d={'MERRY': [12996, 13225, 18225, 20449, 24336, 27556, 27889, 34225, 46225,
             52441, 61009, 62001, 63001, 64009, 70225, 73441, 81225],
   'XMAS': [1024, 1089, 1296, 1369, 1764, 1849, 1936, 2304, 2401, 2601, 2704,
            2809, 2916, 3025, 3249, 3481,3721, 4096, 4356, 4761, 5041, 5184,
            5329, 5476, 6084, 6241, 6724, 7056, 7396, 7569, 7921, 8649, 9025,
            9216, 9604, 9801],
   'TO': [16, 25, 36, 49, 64, 81],
   'ALL': [100, 144, 400, 900]}
首先,我要检查组合:

12996102416100,
12996 1024 16 144,
12996 1024 16 400,
12996 1024 16 900,
之后:
12966102425100
,等等

我需要检查所有可能的组合。另一个解决方案对我来说也很好

我尝试过用很多for循环手动完成它,这很有效

该代码适用于此示例,但我需要将其扩展为最多包含10个键的字典。我不知道如何解决这个问题

此代码显示了具有4个键的字典的示例:

for item in d['MERRY']:
    for item2 in d['XMAS']:
        for item3 in d['TO']:
            for item4 in d['ALL']:
                #make something out of items1,2,3 and 4
                if something == somethingelse:
                    #print(something)
试试这个(赞美@Prune):


product()
为您提供了一个iterable。如果您不想立即将列表放大,请跳过列表理解。

我不会说您不知道。至少,您可以从示例中推断,可以为循环保留嵌套。您需要列表的
itertools.product()
。详见文档,非常感谢!这解决了我的问题从itertools导入产品组合=[p代表产品中的p(*d.values())]代表组合中的c:if something=somethingelse:#打印(something)```
from itertools import product
[p for p in product(*d.values())]