【问题标题】:Comparing three arrays比较三个数组
【发布时间】:2017-04-26 18:23:27
【问题描述】:

我想问一下,为什么返回'True'(或者这样写的代码在做什么):

def isItATriple(first,second,third):
if first[0] == second[0] == third[0] or first[0] != second[0] != third[0]:
    if first[1] == second[1] == third[1] or first[1] !=second[1] != third[1]:
        if first[2] == second[2] == third[2] or first[2] != second[2] != third[2]:
            if (first[3] == second[3] == third[3]) or (first[3] != second[3] != third[3]):
                return True
            else:
                return False
        else:
            return False
    else:
        return False
else:
    return False

print(isItATriple([0,0,0,0],[0,0,0,1],[0,0,0,0]))

【问题讨论】:

  • 因为(first[3] != second[3] != third[3]) ==> (first[3] != second[3]...) && (...second[3] != third[3])。

标签: python arrays if-statement boolean conditional-statements


【解决方案1】:

让我们分析一下:

首先如果:

if first[0] == second[0] == third[0] or \
        first[0] != second[0] != third[0]:

第一个(或之前)是 True - 因为在 0 索引处所有列表都有 0; 如果是这样 - or 之后的条件没有被检查(因为 python 是懒惰的)True or Anything 给出 True。

第二个如果:

if first[1] == second[1] == third[1] or \
            first[1] !=second[1] != third[1]:

与上面完全相同 - 每个列表的 1 个元素是相等的 - 所以这里是真的。

第三个如果:

if first[2] == second[2] == third[2] \
                or first[2] != second[2] != third[2]:

同样的。一般:是的。

第四个如果:

if first[3] == second[3] == third[3] or \
                    first[3] != second[3] != third[3]:

这里 - 第一个条件(之前或)是 False,第二个是 True。所以这就是你的方法返回 True 的原因。

第二个条件被评估为:

0 != 1 != 0

换句话说,这意味着:

0 != 1 and 1 != 0

最后:

True  # because 0 is different than 1;

当您使用这样的运算符时很常见:

1 < x < 10

这意味着:

1 < x and x < 10

但说实话 - 这段代码很丑:)

让我告诉你如何做到这一点nicely

def myIsATriple(first, second, third):
    return first == second == third

列表比较在 python 中效果很好:) 所以你不需要手动做,例子:

myIsATriple([0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0])  # False
myIsATriple([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])  # True
myIsATriple([0, 'a', 0, 0], [0, 'a', 0, 0], [0, 'b', 0, 0])  # False
myIsATriple([0, 'a', 1, 0], [0, 'a', 1, 0], [0, 'a', 1, 0])  # True
myIsATriple([0, {'a': 2}, 1, 0], [0, {'a': 2}, 1, 0], [0, {'a': 3}, 1, 0])  # False
myIsATriple([0, {'a': 2}, 1, 0], [0, {'a': 2}, 1, 0], [0, {'a': 2}, 1, 0])  # True

编码愉快!

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多