我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成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
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]

如果您想使用If,else语句,下面是另一种解决方案:

myList = []
aList = [0, 1, 3]

for l in aList:
    if l==0: myList.append('c')
    elif l==1: myList.append('d')
    elif l==2: myList.append('e')
    elif l==3: myList.append('f')

print(myList)

这将帮助您。

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);

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

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

要检查值是否包含在一组变量中,可以使用内置模块itertools和运算符。

例如:

进口:

from itertools import repeat
from operator import contains

声明变量:

x = 0
y = 1
z = 3

创建值映射(按要检查的顺序):

check_values = (0, 1, 3)

使用itertools允许重复变量:

check_vars = repeat((x, y, z))

最后,使用map函数创建迭代器:

checker = map(contains, check_vars, check_values)

然后,在检查值(按原始顺序)时,使用next():

if next(checker)  # Checks for 0
    # Do something
    pass
elif next(checker)  # Checks for 1
    # Do something
    pass

这比lambda x:x in(变量)有优势,因为运算符是一个内置模块,比使用lambda(必须创建自定义就地函数)更快、更高效。

检查列表中是否存在非零(或False)值的另一个选项:

not (x and y and z)

等效值:

not all((x, y, z))