簡體   English   中英

檢查元組列表中元組的第二個元素是否都相同

[英]check if the second element of tuples in list of tuples are all the same

我想檢查元組列表中元組的第二個元素是否都相同

features = [(a,b), (c,b), (a,d)]

元組的第一個元素可以不同。

x = []
for feature, geom_type in features:
    x.append(geom_type)
y = collections.Counter(x)
print len([i for i in y if y[i]>1])

您使事情變得過於復雜。 您只需要一個集合,然后測試該集合是否僅包含一個元素:

len({g for f, g in features}) <= 1

{expr for targets in iterable}構造是一種集合理解 它從元組中的所有第二個元素構建一個集合。 它只會包含獨特的元素; 如果長度不為1,則存在不同的值。

如果features很大,您可能希望提早紓困,而不是遍歷所有元素。 一些itertools魔術可以做到這一點:

from itertools import dropwhile

def unique(it):
    it = iter(it)
    try:
        next(dropwhile(lambda e, f=next(it): e == f, it))
    except StopIteration:
        return True
    else:
        return False

然后用作:

if unique(g for f, g in features):

所述dropwhile()返回不等於在所述的第一個值的下一個元素it可迭代。 如果沒有這樣的元素,則會引發StopIteration ,並且我們知道整個可迭代對象僅包含一個值。 如果沒有引發StopIteration ,我們會發現它不是唯一的證據。

如果根本沒有元素, it也會返回True

演示:

>>> features = [('a', 'b'), ('c', 'b'), ('a', 'd')]
>>> len({g for f, g in features}) <= 1
False
>>> unique(g for f, g in features)
False
>>> features = [('a', 'b'), ('c', 'b'), ('a', 'b')]
>>> len({g for f, g in features}) <= 1
True
>>> unique(g for f, g in features)
True

對於非常長的列表,構建完整的集合效率不高,因為一旦遇到“不匹配”,您就可以中止。 在這種情況下,應考慮一個普通的舊式命令式循環:

def check_if_second_are_same(lst):
    for item in lst:
        if item[1] != lst[0][1]:
            return False
    return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM