我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成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
你可以团结起来
x = 0
y = 1
z = 3
在一个变量中。
In [1]: xyz = (0,1,3,)
In [2]: mylist = []
将我们的条件更改为:
In [3]: if 0 in xyz:
...: mylist.append("c")
...: if 1 in xyz:
...: mylist.append("d")
...: if 2 in xyz:
...: mylist.append("e")
...: if 3 in xyz:
...: mylist.append("f")
输出:
In [21]: mylist
Out[21]: ['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
我认为这会处理得更好:
my_dict = {0: "c", 1: "d", 2: "e", 3: "f"}
def validate(x, y, z):
for ele in [x, y, z]:
if ele in my_dict.keys():
return my_dict[ele]
输出:
print validate(0, 8, 9)
c
print validate(9, 8, 9)
None
print validate(9, 8, 2)
e