我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成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"]

当前回答

要针对单个值测试多个变量,请执行以下操作:

将变量包装在集合对象中,例如{a,b,c}。使用in运算符测试值是否存储在任何变量中。如果值存储在至少一个变量中,in运算符将返回True。

# ✅ test multiple variables against single value using tuple

if 'a' in (a, b, c):
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------

# ✅ test multiple variables against single value using tuple

if 'a' in {a, b, c}:
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------


# ✅ test multiple variables against single value (OR operator chaining)
if a == 'a' or b == 'a' or c == 'a':
    print('value is stored in at least one of the variables')

资料来源:https://bobbyhadz.com/blog/python-test-multiple-variables-against-single-value

其他回答

这将帮助您。

def test_fun(val):
    x = 0
    y = 1
    z = 2
    myList = []
    if val in (x, y, z) and val == 0:
        myList.append("C")
    if val in (x, y, z) and val == 1:
        myList.append("D")
    if val in (x, y, z) and val == 2:
        myList.append("E")

test_fun(2);
#selection
: a=np.array([0,1,3])                                                                                                                                                 

#options
: np.diag(['c','d','e','f']) 
array([['c', '', '', ''],
       ['', 'd', '', ''],
       ['', '', 'e', ''],
       ['', '', '', 'f']], dtype='<U1')

现在我们可以使用as[row,col]选择器,它的作用就像任何(…)条件一样:

#list of options[sel,sel]
: np.diag(['c','d','e','f'])[a,a]                                                                                                                                     

 array(['c', 'd', 'f'], dtype='<U1')

问题

而测试多个值的模式

>>> 2 in {1, 2, 3}
True
>>> 5 in {1, 2, 3}
False

非常易读,在许多情况下都可以使用,但有一个陷阱:

>>> 0 in {True, False}
True

但我们希望

>>> (0 is True) or (0 is False)
False

解决方案

前面表达式的一个概括是基于ytpilai的答案:

>>> any([0 is True, 0 is False])
False

可以写成

>>> any(0 is item for item in (True, False))
False

虽然此表达式返回正确的结果,但其可读性不如第一个表达式:-(

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

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

还有一种方法:

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

if any(i in [0] for i in[x,y,z]):
    mylist.append("c")
if any(i in [1] for i in[x,y,z]):
    mylist.append("d")
if any(i in [2] for i in[x,y,z]):
    mylist.append("e")
if any(i in [3] for i in[x,y,z]):
    mylist.append("f")

它是列表理解和任何关键字的混合。