Python:确定列表中的所有项目是否都相同 [英] Python: determine if all items of a list are the same item

查看:102
本文介绍了Python:确定列表中的所有项目是否都相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的某些代码中,我将一系列对象放入列表中,并根据其属性(即字符串)构建了另一个列表.我需要确定第二个列表中的所有项目是否都具有完全相同的值,而无需事先知道它是哪个值,然后返回布尔值,以便我可以根据结果在代码中做不同的事情.

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 code 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.

为使示例更清楚,一个理想的函数"all_same"将像这样工作:

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

我当时想列出一个唯一元素,然后检查其长度是否为1,但是我不确定这是否是最优雅的解决方案.

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)

示例:

>>> 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

这篇关于Python:确定列表中的所有项目是否都相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆