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

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

其他回答

如果您想使用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)

还有一种方法:

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

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

这里提供的所有优秀答案都集中于原始海报的具体要求,并集中于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在列表中以组合形式存在,但不是单独的单词。测试“腐烂”会失败,但如果列表中的一项是“腐烂在地狱”,那也会失败。结果是,如果使用此方法,请注意搜索条件,并注意它确实有此限制。

要检查值是否包含在一组变量中,可以使用内置模块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))

单线解决方案:

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

Or:

mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]