In some of my code I put a series of objects in a list and I build an additional list out of their attributes, which is a string. I need to determine if all the items in this second list have the exact same value, without knowing beforehand which value it is, and return a bool so that I can do different things in my co开发者_JS百科de depending on the result.
I can't know the names of the properties beforehand, that is why I'm trying to make something as generic as possible.
To make the example clear, an ideal function, called "all_same" would work like this:
>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False
I was thinking of making a list of unique elements and then check if its length is 1, but I'm not sure if it's the most elegant solution out there.
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
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
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 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)
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
精彩评论