简体   繁体   English

Python列表:检查所有项目是否相同

[英]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.我有一个 python 字符串列表,想检查所有列表项值是否相同。

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/then但后来我需要检查列表值的所有组合,如果列表有很多项目则需要很多硬编码。

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 WRONG_LIST 中的错误列表并不是所有的项目值字符串都是一些

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:更新以包含来自@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:如果要检查列表中的所有项目是否相同,可以检查列表集合的长度是否等于 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.并为您的测试用例返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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