我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成Python。所以说:

x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0:
    mylist.append("c")
if x or y or z == 1:
    mylist.append("d")
if x or y or z == 2:
    mylist.append("e")
if x or y or z == 3: 
    mylist.append("f")

其将返回以下列表:

["c", "d", "f"]

当前回答

你可以通过两种方式发展它

    def compareVariables(x,y,z):
        mylist = []
        if x==0 or y==0 or z==0:
            mylist.append('c')
        if  x==1 or y==1 or z==1:
            mylist.append('d')
        if  x==2 or y==2 or z==2:
            mylist.append('e')
        if  x==3 or y==3 or z==3:
            mylist.append('f')
        else:
            print("wrong input value!")
        print('first:',mylist)

        compareVariables(1, 3, 2)

Or

    def compareVariables(x,y,z):
        mylist = []
        if 0 in (x,y,z):
             mylist.append('c')
        if 1 in (x,y,z):
             mylist.append('d')
        if 2 in (x,y,z):
             mylist.append('e')
        if 3 in (x,y,z):
             mylist.append('f')
        else:
             print("wrong input value!")
        print('second:',mylist)

        compareVariables(1, 3, 2)

其他回答

您的问题更容易通过字典结构解决,如:

x = 0
y = 1
z = 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]

不带if的用法示例:

x,y,z = 0,1,3
values = {0:"c",1:"d",2:"e",3:"f"} # => as if usage
my_list = [values[i] for i in (x,y,z)]

print(my_list)

这里提供的所有优秀答案都集中于原始海报的具体要求,并集中于Martijn Pieters提出的if1in{x,y,z}解决方案。他们忽略了问题的更广泛含义:如何针对多个值测试一个变量?如果使用字符串,则提供的解决方案不适用于部分命中,例如:测试字符串“Wild”是否为多个值

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

or

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

对于这种情况,转换为字符串是最简单的

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

然而,需要注意的是,正如@codeforester所提到的,这个方法会丢失单词boundries,如:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

这三个字母rot在列表中以组合形式存在,但不是单独的单词。测试“腐烂”会失败,但如果列表中的一项是“腐烂在地狱”,那也会失败。结果是,如果使用此方法,请注意搜索条件,并注意它确实有此限制。

如果没有dict,请尝试以下解决方案:

x, y, z = 0, 1, 3    
offset = ord('c')
[chr(i + offset) for i in (x,y,z)]

并给出:

['c', 'd', 'f']

写x或y或z==0的直接方法是

if any(map((lambda value: value == 0), (x,y,z))):
    pass # write your logic.

但我认为,你不喜欢这种方式很难看。

另一种方式(更好)是:

0 in (x, y, z)

顺便说一句,很多如果可以写成这样

my_cases = {
    0: Mylist.append("c"),
    1: Mylist.append("d")
    # ..
}

for key in my_cases:
    if key in (x,y,z):
        my_cases[key]()
        break