首页 > 解决方案 > 卡在 Python 中的嵌套 for 循环上

问题描述

我正在尝试做一个嵌套的 for 循环,例如将比较相邻的元素。假设我有一个 [2,3,4,5,6] 的列表,我想比较 2 到 3、2 到 4,一直到 6。之后,我想去 3 但我没有想回去比较3和2,不想和自己比较。有没有办法做到这一点?我不断收到 NoneType 错误。提前致谢!

标签: pythonloopsnested

解决方案


您可以创建一个查找表来存储以前处理的项目。

你可以尝试这样的事情:

lst = [2,3,4,5,6]

lut = {item: {} for item in lst} # lookup table

for item1 in lst:
    for item2 in lst:
        if item1 == item2: continue # skip comparing to self

        min_val, max_val = sorted([item1, item2])
        if lut[min_val].get(max_val): continue # skip if already processed

        print(item1, item2) # do the processing here

        lut[min_val][max_val] = True # mark the items processed

输出:

2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6

推荐阅读