Python 需要编写一个函数来接收颜色列表,并输出它们的负颜色(来自dict的成对颜色)

Python 需要编写一个函数来接收颜色列表,并输出它们的负颜色(来自dict的成对颜色),python,function,loops,dictionary,Python,Function,Loops,Dictionary,我使用列表理解完成了这项工作,但我的代码无论如何都不能令人满意。如何使其更短、更高效?请注意,我无法更改colsdict,最好不要使用任何库 def RevertCol(L): cols = {'white': 'black', 'red' : 'green', 'yellow': 'blue'} negative = [] keys = cols.keys() values = cols.items() for col in L: if

我使用列表理解完成了这项工作,但我的代码无论如何都不能令人满意。如何使其更短、更高效?请注意,我无法更改
cols
dict,最好不要使用任何库

def RevertCol(L):
    cols = {'white': 'black', 'red' : 'green', 'yellow': 'blue'}
    negative = []
    keys = cols.keys()
    values = cols.items()

    for col in L:
        if col in keys:
            negative.append(cols.get(col))
        else:
            for m, t in values:
                if t == col:
                    negative.append(m)
    return negative
输入:

RevertCol(['red', 'white']) 
['green', 'black']
out:

RevertCol(['red', 'white']) 
['green', 'black']

有没有理由不把所有的颜色都作为字典上的键?例如:

cols = {'white': 'black', 'red' : 'green', 'yellow': 'blue', 'black': 'white', 'green': 'red', 'blue': 'yellow'}
然后,只需检查dict中存在的每种颜色并返回值,就可以得到答案

如果不想手动展开dict,可以通过编程方式进行:

inverse_dict = { v:k for (k,v) in cols.items() }
此外,您不需要获取cols.keys()来检查dict中是否存在键

if col in cols
这更有效,因为它是哈希表检查(~O(1))而不是列表检查(O(n))

将所有这些加起来,您可以得到如下解决方案:

def revert_color(colors):
    colors = {'white': 'black', 'red' : 'green', 'yellow': 'blue'}
    inverse_colors = { v:k for (k,v) in cols.items() }

    complete_inverse = {**colors, **inverse_colors}

    # If color exists in the dict, return the inverse, else return the color itself.
    return [ complete_inverse[color] if color in complete_inverse else color for color in colors ]

为了使您的方法更快、更易于阅读,您可以将所有颜色否定存储在一个贴图中

def RevertCol(L):
    cols = [('white', 'black'), ('red', 'green'), ('yellow', 'blue')]
    col_to_negative = {}
    col_to_negative.update(cols)
    col_to_negative.update((value, key) for key, value in cols)

    return [col_to_negative[col] for col in L]

您还可以预先计算一次
col\u to\u negative
,然后每次调用都使用它

反转第一个字典,将它们组合起来,然后只需获取您需要的

def RevertCol2(L):
    cols = {'white': 'black', 'red': 'green', 'yellow': 'blue'}
    cols.update({value: key for key, value in cols.items()})
    return [cols[i] for i in L if i in cols.keys()]

它读起来更清晰(对我来说),并且消除了循环。

复制您的字典并添加还原的条目。然后使用列表:

def RevertCol(L):
    cols = {'white': 'black', 'red' : 'green', 'yellow': 'blue'}
    cols_new = cols.copy()
    cols_new.update(dict([(value, key) for key, value in cols.items()]))
    return [cols_new.get(col) for col in L]

谢谢,行得通。需要一些时间来消化最后的回击,我将花时间学习即将到来的夜晚的语法。你的解决方案肯定有效,只是大学的任务要求不要更改COL。不管怎样,我从你的代码中学到了很多,谢谢你。我会努力掌握你的语法,看起来真的很棒。那很优雅,我在想这个,虽然我不知道。现在我知道了。谢谢。您的代码似乎是最简洁的,同时还保持了不可更改的cols条件(尽管在完美世界中它并不存在)。谢谢。