检查数组中的值是否相等

时间:2017-10-04 06:39:09

标签: python

有人可以解释为什么使用以下代码我不会收到消息Arguments len do not match如果不是所有的值都相等吗?

values = [len(self._parsed_arguments['inputs']), 
         len(self._parsed_arguments['files']), 
         len(self._parsed_arguments['names']), 
         len(self._parsed_arguments['types'])]

        print(values)
        if all(v != values[0] for v in values):
            print("Arguments len do not match")
            sys.exit(1)
        else:
            print("what the hell")

结果:

[1, 1, 2, 1]
what the hell

也试过

len(self._parsed_arguments['inputs'] != len(self._parsed_arguments['files'] != len(self._parsed_arguments['names'] != len(self._parsed_arguments['types'])

1 个答案:

答案 0 :(得分:2)

第一种方式,已经在Julien的答案中提到:any是正确的,所以写:

if any(v != values[0] for v in values):
    print("Arguments len do not match")

另一种方式(可能更直观,取决于数组的大小也更快):检查,如果集合的长度恰好是一个:

if len(set(values)) > 1:
    print("Arguments len do not match")
相关问题