python - 卡在 Python 中的嵌套 for 循环上
问题描述
我正在尝试做一个嵌套的 for 循环,例如将比较相邻的元素。假设我有一个 [2,3,4,5,6] 的列表,我想比较 2 到 3、2 到 4,一直到 6。之后,我想去 3 但我没有想回去比较3和2,不想和自己比较。有没有办法做到这一点?我不断收到 NoneType 错误。提前致谢!
解决方案
您可以创建一个查找表来存储以前处理的项目。
你可以尝试这样的事情:
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
推荐阅读
- r - 如何将以下代码包装到 R 中的 for 循环中?
- google-apps-script - 用户驱动器在没有共享文件的情况下的使用情况
- javascript - Javascript 代码有太多的 if 语句,我需要一个替代方案
- powershell - 通过 csv 文件问题将新打印机添加到新打印服务器
- java - 在 WEAR OS 上启动 gmap 所需的 READ_SETTINGS 权限
- angular - 使用 FAB 启动导航器
- java - 当代理类不被接受时,Spring 的 HTTPInvoker 机制允许哪些序列化攻击?
- c++ - 制作线程 C2672 和 C2893 错误代码 (c++)
- r - R Caret,如何在训练和应用数据集时具有相同的功能
- c# - 从字符串c#中删除多个值