Python:确定列表的所有项目是否为同一项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3787908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:45:29  来源:igfitidea点击:

Python: determine if all items of a list are the same item

pythonlist

提问by Einar

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.

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

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:

为了使示例清晰,一个名为“all_same”的理想函数将如下工作:

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

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

采纳答案by FogleBird

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

回答by wheaties

You could cheat and use set:

你可以欺骗和使用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

回答by FogleBird

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 isinstead of ==.)

我最初将您解释为测试身份(“相同项目”),但您实际上是在测试相等性(“相同值”)。(如果您正在测试身份,请使用is而不是 ==。)

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

(但是,恕我直言,您不妨使用通用版本——它在列表上运行得非常好。)

回答by tokland

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)

回答by Jonas K

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)

回答by rezakamalifard

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

最好的方法是使用 Python 集合。你需要这样定义all_same

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

回答by Landon Powell

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