我有一个需要进行冒泡排序的项目列表。如果在大多数结果集中项目j
的排名高于项目i
,则在FullList
中对换项目j
和项目i
。除了一个小问题,我有一个非常简单的泡沫排序。当FullList
项目没有出现在其中一个结果集中时,我得到一个关键错误。我需要付出一定的代价来弥补这一点,否则我的循环会变得非常复杂,包含大量的if语句。如果我可以将一个记号值(例如20)赋值给字典中不存在的任何值,我的循环将是完美的。谁能帮我吗?将一个临时值分配给循环中的变量python
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'
问题标题与问题描述有什么关系? – abarnert 2012-07-20 22:18:45
@abarnert我试图给一个循环中的变量分配一个临时值,以便做一些事情。我认为这是一个合适的标题? – adohertyd 2012-07-20 22:22:57
@adohertyd:我收回了我的答案,因为你的代码和你的理解需要更多的帮助,而不是链接一个简单的函数来解决你的问题。您可以尝试通过在freenode.net上加入#python IRC频道来获得帮助。 – orlp 2012-07-20 22:25:13