我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成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"]
如果您非常懒惰,可以将值放入数组中。例如
list = []
list.append(x)
list.append(y)
list.append(z)
nums = [add numbers here]
letters = [add corresponding letters here]
for index in range(len(nums)):
for obj in list:
if obj == num[index]:
MyList.append(letters[index])
break
你也可以把数字和字母放在字典里,这样做,但这可能比简单的if语句复杂得多。这就是你试图变得特别懒惰的原因:)
还有一件事,你的
if x or y or z == 0:
将编译,但不是以您希望的方式编译。当您简单地将变量放入if语句中时(示例)
if b
程序将检查变量是否为空。写上述语句的另一种方式(更有意义)是
if bool(b)
Bool是python中的一个内置函数,它基本上执行验证布尔语句的命令(如果你不知道这是什么,那就是你现在想在If语句中做的:)
我发现的另一种懒惰方式是:
if any([x==0, y==0, z==0])
要针对单个值测试多个变量,请执行以下操作:
将变量包装在集合对象中,例如{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
如Martijn Pieters所述,正确且最快的格式是:
if 1 in {x, y, z}:
根据他的建议,您现在可以有单独的if语句,这样Python可以读取每个语句,无论前者是True还是False。例如:
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")
...
这会起作用,但如果你喜欢使用字典(看看我在那里做了什么),你可以通过创建一个将数字映射到你想要的字母的初始字典,然后使用for循环来清理这个问题:
num_to_letters = {0: "c", 1: "d", 2: "e", 3: "f"}
for number in num_to_letters:
if number in {x, y, z}:
mylist.append(num_to_letters[number])
你可以通过两种方式发展它
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或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