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

当前回答

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

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
list=[]
dict = {0: 'c', 1: 'd', 2: 'e', 3: 'f'}
if x in dict:
    list.append(dict[x])
else:
    pass

if y in dict:
    list.append(dict[y])
else:
    pass
if z in dict:
    list.append(dict[z])
else:
    pass

print list
#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')

您误解了布尔表达式的工作原理;它们不像一个英语句子,你猜你说的是这里所有名字的相同比较。您正在查找:

if x == 1 or y == 1 or z == 1:

否则,x和y将单独计算(如果为0,则为False,否则为True)。

您可以对元组使用包含测试来缩短这一时间:

if 1 in (x, y, z):

或者更好:

if 1 in {x, y, z}:

使用集合来利用恒定成本成员资格测试(即,无论左手操作数是什么,都需要固定的时间)。

解释

当您使用或时,python会将运算符的每一面视为单独的表达式。表达式x或y==1首先被视为x的布尔测试,如果为False,则测试表达式y==1。

这是由于运算符优先级。or运算符的优先级低于==测试,因此先对后者求值。

然而,即使情况并非如此,表达式x或y或z==1实际上被解释为(x或y)==1,这仍然无法实现您期望的效果。

x、y或z将计算为“truthy”的第一个参数,例如不是False、数字0或空(有关Python在布尔上下文中视为False的详细信息,请参见布尔表达式)。

对于x=2的值;y=1;z=0,x或y或z将解析为2,因为这是参数中的第一个类真值。那么2==1将为False,即使y==1为True。

反过来也一样;针对单个变量测试多个值;x==1或2或3将因相同原因而失败。在{1,2,3}中使用x==1或x==2或x==3或x。

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

将变量包装在集合对象中,例如{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

要使用一个值测试多个变量:如果{a,b,c}中为1:

要使用一个变量测试多个值:如果{1,2,3}中有一个: