python - 将临时值分配给循环python中的变量

标签 python list if-statement dictionary

我有一个需要进行冒泡排序的项目列表。冒泡排序的标准是,如果在大多数结果集中项目 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/

相关文章:

python - Pandas :从MultiIndex中的日期选择

java - Java中数组的文件列表

jQuery If/Else If 不起作用

if-statement - is if x <> empty 与 if not isempty(x) 相同

r - 根据条件(唯一值的长度)跨多个列进行变异

python - 使用 setuptools/distribute 打包资源

python - Docker 容器是否共享一个 Python GIL?

python - 将日期转换为一年中的某一天,而不使用日期时间

list - 键入要求非空列表的最佳方式是什么(不使用 Scalaz)?

python - 如何将两个列表合并为一个,同时更改某些值?