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

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


当前回答

你可以:

reduce(and_, (x==yourList[0] for x in yourList), True)

python让你导入operator.and_这样的操作符是相当烦人的。从python3开始,还需要导入functools.reduce。

(您不应该使用此方法,因为如果它发现不相等的值,它不会中断,而是会继续检查整个列表。这里只是作为完整性的回答。)

其他回答

您可以将列表转换为集合。集合不能有重复项。所以如果原始列表中的所有元素都是相同的,那么集合就只有一个元素。

if len(set(input_list)) == 1:
    # input_list has all identical elements.

简单的解决方案是应用set on list

如果所有元素都相同,len将为1,否则大于1

lst = [1,1,1,1,1,1,1,1,1]
len_lst = len(list(set(lst)))

print(len_lst)

1


lst = [1,2,1,1,1,1,1,1,1]
len_lst = len(list(set(lst)))
print(len_lst)

2
def allTheSame(i):
    j = itertools.groupby(i)
    for k in j: break
    for k in j: return False
    return True

适用于Python 2.4,它没有“all”。

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

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

不管怎样,这是最近在python想法邮件列表中出现的。事实证明,已经有一个itertools配方可以做到这一点

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

据说它的性能非常好,有一些不错的属性。

短路:一旦发现第一个不相等的项,它就会停止从可迭代对象中消费项目。 不要求项是可哈希的。 它是懒惰的,只需要O(1)个额外的内存来进行检查。

换句话说,我不能把提出这个解决方案的功劳占为己有,甚至我也不能把找到它的功劳占为己有。