摄影:产品经理
与产品经理环游世界的日子
假设你有3个数字变量a, b, c。还有三个数字变量x,y,z,现在需要优雅地实现:
if (a == x and b == y and c == z) or (a == x and b == z and c == y) or (a == y and b == x and c == z) or (a == y and b == z and c == x) or (a == z and b == y and c == z) or (a == z and b == z and c == y):
print('abc与xyz相等!')
我们给出4个办法。
稍稍简化了一丁点:
if (a, b, c) == (x, y, z) or (a, b, c) == (x, z, y) or (a, b, c) == (y, x, z) or (a, b, c) == (y, z, x) or (a, b, c) == (z, x, y) or (a, b, c) == (z, y, x):
print('abc与xyz相等!')
又少了一些代码:
if (a, b, c) in {(x, y, z), (x, z, y), (y, x, z), (y, z, x), (z, x, y), (z, y, x)}:
print('abc与xyz相等!')
代码大幅度减少:
from itertools import permutations
if (a, b, c) in permutations([x, y, z]):
print('abc与xyz相等')
进一步优化:
if {a, b, c} == {x, y, z}:
print('abc与xyz相等')