我试图制作一个函数,将多个变量与一个整数进行比较,并输出一个三个字母的字符串。我想知道是否有办法将其翻译成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"]
问题
而测试多个值的模式
>>> 2 in {1, 2, 3}
True
>>> 5 in {1, 2, 3}
False
非常易读,在许多情况下都可以使用,但有一个陷阱:
>>> 0 in {True, False}
True
但我们希望
>>> (0 is True) or (0 is False)
False
解决方案
前面表达式的一个概括是基于ytpilai的答案:
>>> any([0 is True, 0 is False])
False
可以写成
>>> any(0 is item for item in (True, False))
False
虽然此表达式返回正确的结果,但其可读性不如第一个表达式:-(
要针对单个值测试多个变量,请执行以下操作:
将变量包装在集合对象中,例如{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 or y=0 or z=0 is equivalent to x*y*z = 0
x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0
x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0
让我们映射到位:“c”:1“d”:0xb10“e”:0xb 100“f”:0xb1 000
isc的关系(为“c”):
if xyz=0 then isc=1 else isc=0
使用数学if公式https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315
[c] :(xyz=0和isc=1)或((xyz=0和isc=1)或(isc=0))和(isc=0))
[d] :((x-1)(y-1)(z-1)=0且isc=2)或((xyz=0且isd=2)或(isc=0))
...
通过以下逻辑连接这些公式:
逻辑和是方程的平方和逻辑或是方程式的乘积
你会得到一个总方程式求和,你就有了求和的总公式
那么和1是c,和2是d,和4是e,和5是f
在此之后,您可以形成预定义的数组,其中字符串元素的索引将对应于就绪字符串。
array[sum]提供字符串。
单线解决方案:
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)]
如果您非常懒惰,可以将值放入数组中。例如
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])