Python: 确定列表中的所有项是否都是相同的项

在我的一些代码中,我将一系列对象放在一个列表中,然后用它们的属性构建一个额外的列表,这个列表是一个字符串。我需要确定第二个列表中的所有项是否具有完全相同的值,而不需要事先知道它是哪个值,然后返回一个 bool,这样我就可以根据结果在代码中执行不同的操作。

我不能预先知道属性的名称,这就是为什么我试图使一些尽可能通用。

为了让示例更清楚,一个理想的函数,称为“ all _ same”,应该是这样工作的:

>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False

我在考虑列一个独特元素的列表,然后检查它的长度是否为1,但我不确定这是否是最优雅的解决方案。

125609 次浏览

You could cheat and use set:

def all_same( items ):
return len( set( items ) ) == 1 #== len( items )

or you could use:

def all_same( items ):
return all( map(lambda x: x == items[0], items ) )

or if you're dealing with an iterable instead of a list:

def all_same( iterable ):
it_copy = tee( iterable, 1 )
return len( set( it_copy) ) == 1
def all_same(items):
return all(x == items[0] for x in items)

Example:

>>> def all_same(items):
...     return all(x == items[0] for x in items)
...
>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False
>>> all_same([])
True

I originally interpreted you to be testing identity ("the same item"), but you're really testing equality ("same value"). (If you were testing identity, use is instead of ==.)

def all_same(items):
it = iter(items)
for first in it:
break
else:
return True  # empty case, note all([]) == True
return all(x == first for x in it)

The above works on any iterable, not just lists, otherwise you could use:

def all_same(L):
return all(x == L[0] for x in L)

(But, IMHO, you might as well use the general version—it works perfectly fine on lists.)

This works both for sequences and iterables:

def all_same(items):
it = iter(items)
first = next(it, None)
return all(x == first for x in it)

This is likely to be faster if you know values are in a list.

def all_same(values):
return values.count(values[0]) == len(values)

Best way to do this is to use Python sets.You need to define all_same like this:

def all_same(items):
return len(set(items)) < 2

Test:

>>> def all_same(items):
...     return len(set(items)) < 2
...
>>>
>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False
>>> property_list = []
>>> all_same(property_list)
True

I created this snippet of code for that same issue after thinking it over. I'm not exactly sure if it works for every scenario though.

def all_same(list):
list[0]*len(list) == list