向 "or" 语句添加参数的更简单方法?

Easier way to add arguments to an "or" statement?

有没有更简单的方法来执行以下操作而无需我写出 outputbodypixel == everytime?理想情况下,我想从一个列表中提取数据,我可以在其中添加 #ebebeb#ececec#212121.

if(outputbodypixel == "#356044" or outputbodypixel == "#22402b" or
   outputbodypixel == "#213f2c" or outputbodypixel == "#356043" or
   outputbodypixel == "#22402c" or outputbodypixel == "#346044"):
    output_body = "green"
elif(outputbodypixel == "#7c3d15" or outputbodypixel == "#493613" or
     outputbodypixel == "#4a3612" or outputbodypixel == "#6a553e" or
     outputbodypixel == "#785735" or outputbodypixel == "#5e4b37" or
     outputbodypixel == "#6a553e" or outputbodypixel == "#86623c" or
     outputbodypixel == "#8b4f0d" or outputbodypixel == "#7c3d14" or
     outputbodypixel == "#6a553d" or outputbodypixel == "#7c3d14" or
     outputbodypixel == "#6a553d" or outputbodypixel == "#7c3d14" or
     outputbodypixel == "#87623c" or outputbodypixel == "#6e3612" or
     outputbodypixel == "#87613c"):
    output_body = "brown"
elif(outputbodypixel == "#8b8b8a" or outputbodypixel == "#8b8b8b" or
     outputbodypixel == "#8b8a8b"):
    output_body = "silver"
else:
    output_body = "NOT DEFINED"

我正在使用 Python 3.x。

只需将 in 与每个条件的所有可能值的元组(或列表,如果你已经有一个列表)一起使用,这与询问 outputbodypixel 是否是一个完全相同价值 or 其他 or 其他等

if outputbodypixel in ("#356044", "#22402b", "#213f2c", "#356043", "#22402c", "#346044"):
    output_body = "green"
elif outputbodypixel in ("#7c3d15", "#493613", "#4a3612", "#6a553e", "#785735", "#5e4b37", "#6a553e", "#86623c", "#8b4f0d", "#7c3d14", "#6a553d", "#7c3d14", "#6a553d", "#7c3d14", "#87623c", "#6e3612", "#87613c"):
    output_body = "brown"
elif outputbodypixel in ("#8b8b8a", "#8b8b8b", "#8b8a8b"):
    output_body = "silver"
else:
    output_body = "NOT DEFINED"

您可以创建这样的函数:

def output(value):
    return f"outputbodypixel == #{value}"

#You can call the function like this:

if output(12345) or output(5678):
    pass

这只是为了让您不必每次都输入“outputbodypixel”。如果您想从列表中获取值,只需在创建的函数内创建一个 for 循环,循环遍历列表的值。希望这有帮助 :D

对于同样具有稳定性能的解决方案,您可以为此使用 dictdefaultdict。如果使用 defaultdict,则可以按如下方式将源 dict 传递到构造函数中。

from collections import defaultdict


pixel = defaultdict(lambda: 'NOT DEFINED', {
    '#356044': 'green',
    '#22402b': 'green',
    '#7c3d15': 'brown',
    '#8b8b8a': 'silver',
    '#8b8b8b': 'silver'
})

pixel['#356044']
# green

pixel['#8b8b8b']
# silver

pixel['#something-else']
# NOT DEFINED