我需要一个函数,它接受一个列表并输出True,如果输入列表中的所有元素使用标准相等运算符计算彼此相等,否则输出False。

我觉得最好是遍历列表,比较相邻的元素,然后与所有结果布尔值。但我不知道最python的方法是什么。


当前回答

这是另一个选项,对于长列表,比len(set(x))==1快(使用短路)

def constantList(x):
    return x and [x[0]]*len(x) == x

其他回答

关于使用reduce()和lambda。这里有一个工作代码,我个人认为比其他一些答案更好。

reduce(lambda x, y: (x[1]==y, y), [2, 2, 2], (True, 2))

返回一个元组,其中第一个值是布尔值,如果所有项都相同或不相同。

如果你对一些更有可读性的东西感兴趣(但当然不是那么高效),你可以尝试:

def compare_lists(list1, list2):
    if len(list1) != len(list2): # Weed out unequal length lists.
        return False
    for item in list1:
        if item not in list2:
            return False
    return True

a_list_1 = ['apple', 'orange', 'grape', 'pear']
a_list_2 = ['pear', 'orange', 'grape', 'apple']

b_list_1 = ['apple', 'orange', 'grape', 'pear']
b_list_2 = ['apple', 'orange', 'banana', 'pear']

c_list_1 = ['apple', 'orange', 'grape']
c_list_2 = ['grape', 'orange']

print compare_lists(a_list_1, a_list_2) # Returns True
print compare_lists(b_list_1, b_list_2) # Returns False
print compare_lists(c_list_1, c_list_2) # Returns False

或者使用numpy的diff方法:

import numpy as np
def allthesame(l):
    return np.all(np.diff(l)==0)

并呼吁:

print(allthesame([1,1,1]))

输出:

True

我想做的事:

not any((x[i] != x[i+1] for i in range(0, len(x)-1)))

as any一旦找到True条件就会停止搜索可迭代对象。

我怀疑这是“最python化的”,但类似于:

>>> falseList = [1,2,3,4]
>>> trueList = [1, 1, 1]
>>> 
>>> def testList(list):
...   for item in list[1:]:
...     if item != list[0]:
...       return False
...   return True
... 
>>> testList(falseList)
False
>>> testList(trueList)
True

会成功的。