我有一个需要进行冒泡排序的项目列表。冒泡排序的标准是,如果在大多数结果集中项目 j
的排名高于项目 i
,则将项目 j
与项目 交换我
在FullList
中。除了一个小问题之外,我想出了一个非常简单的冒泡排序。当 FullList
项未出现在结果集中之一时,我收到关键错误。我需要输入一个值来补偿这一点,否则我的循环会因大量 if 语句而变得非常复杂。如果我可以将一个标记值(例如 20)分配给字典中不存在的任何值,那么我的循环将是完美的。谁能帮帮我吗?
FullList = [B,C,A,D,H,E,F,G]
Results1 = {'A':1,'B':2,'C':3,'D':4,'E':5}
Results2 = {'B':1,'D':2,'G':3,'F':4,'E':5}
Results3 = {'C':1,'D':2,'B':3,'A':4,'H':5}
Pseudo Code:
switch = True
while(switch):
switch = False
for i in range(len(FullList)-1):
if FullList[i+1]<FullList[i] in Results1 & 2:
FullList[i],FullList[i+1] = FullList[i+1],FullList[i]
switch = True
elif FullList[i+1]<FullList[i] in Results1 & 3:
FullList[i],FullList[i+1] = FullList[i+1],FullList[i]
switch = True
elif FullList[i+1]<FullList[i] in Results2 & 3:
FullList[i],FullList[i+1] = FullList[i+1],FullList[i]
switch = True
Key-Error: 'A' not in 'Results2'
最佳答案
不知道你到底想做什么,但似乎 get(key[, default])
就是你所需要的,你可以查看此 here 的详细信息
就您而言,Results2.get('A', 20)
将为您提供 20
关于python - 将临时值分配给循环python中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11587588/