[英]Retrieving if all objects in a list have the same value for an attribute in python
[英]Test if all objects have same member value
我在python 中有一個簡單的類:
class simple(object):
def __init__(self, theType, someNum):
self.theType = theType
self.someNum = someNum
稍后在我的程序中,我創建了這個類的多個實例,即:
a = simple('A', 1)
b = simple('A', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('C', 5)
allThings = [a, b, c, d, e] # Fails "areAllOfSameType(allThings)" check
a = simple('B', 1)
b = simple('B', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('B', 5)
allThings = [a, b, c, d, e] # Passes "areAllOfSameType(allThings)" check
我需要測試allThings
中的所有元素是否對allThings
具有相同的值。 我將如何為此編寫通用測試,以便我將來可以包含新的“類型”(即D
、 E
、 F
等)而不必重新編寫我的測試邏輯? 我可以想出一種通過直方圖來做到這一點的方法,但我認為有一種“pythonic”的方法可以做到這一點。
只需使用all()
函數將每個對象與第一個項目的類型進行比較:
all(obj.theType == allThings[0].theType for obj in allThings)
如果列表為空,也不會出現IndexError
。
all()
短路,因此如果一個對象與另一個對象的類型不同,則循環立即中斷並返回False
。
您可以為此使用itertools 配方: all_equal
(逐字復制):
from itertools import groupby
def all_equal(iterable):
"Returns True if all the elements are equal to each other"
g = groupby(iterable)
return next(g, True) and not next(g, False)
然后您可以使用訪問theType
屬性的生成器表達式調用它:
>>> allThings = [simple('B', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)]
>>> all_equal(inst.theType for inst in allThings)
True
>>> allThings = [simple('A', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)]
>>> all_equal(inst.theType for inst in allThings)
False
鑒於它實際上是作為配方放在 Python 文檔中的,這似乎是解決此類問題的最佳(或至少是推薦的)方法之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.