简体   繁体   中英

Python list: check if all items are the same or not

I have a python list of strings and want to check if all list item values are the same or not.

I tried to use condition if/then but then I'd need to check all combinations of list values and if list have many items then need to many hard code.

if item1 != item1 and item1 != item2 and item1 !=item2 ....... :
    check='wrong'
else:
    check= 'correct'

Input:

listOfStrings = ['ep:1000' , 'ep:4444', 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000']

UPDATE

Example:

CORRECT_LIST = ['ep:1000' , 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000']

IN correct list all items values are the same, then my list is correct

WRONG_LIST = ['ep:1000' , 'ep:4444', 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000']

WRONG_LIST in the wrong list is not all items values string are the some

The code snippet you have provided looks a little weird. But if I understand correctly, you are trying to check for the number of unique values in a list.

One way to do it is to convert it to a set and check its length.

len(set(listOfStrings))

Updated to include working code snippet from @iGian:

check = 'wrong' if len(set(list_of_strings)) > 1 else 'correct'

IN correct list all items values are the same, then my list is correct

If you want to check if all items in a list are the same you can check if the lenght of the set of the list is equal to 1:

len(set(listOfStrings)) == 1 

Characteristic for a set is that every element is unique namely to that set.

This compares every element of the list to the first one:

listOfStrings = ['ep:1000' , 'ep:4444', 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000']
check = all(x == listOfStrings[0] for x in listOfStrings)

And returns false for your test case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM