简体   繁体   English

检查元组列表中元组的第二个元素是否都相同

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

I would like to check if the second element of tuples in list of tuples are all the same 我想检查元组列表中元组的第二个元素是否都相同

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

The first element of the tuple can be different. 元组的第一个元素可以不同。

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

You are overcomplicating matters. 您使事情变得过于复杂。 All you need is a set, then test if the set contains just one element: 您只需要一个集合,然后测试该集合是否仅包含一个元素:

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

The {expr for targets in iterable} construct is a set comprehension ; {expr for targets in iterable}构造是一种集合理解 it builds a set from all the second elements in your tuples. 它从元组中的所有第二个元素构建一个集合。 It'll only hold the unique elements; 它只会包含独特的元素; if it's length is not 1 then there were at different values. 如果长度不为1,则存在不同的值。

If features is very large, you may want to bail out early rather than iterate over all elements; 如果features很大,您可能希望提早纾困,而不是遍历所有元素。 some itertools magic could do that: 一些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

then use as: 然后用作:

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

The dropwhile() returns the next element that is not equal to the very first value in the it iterable. 所述dropwhile()返回不等于在所述的第一个值的下一个元素it可迭代。 If there is no such element, StopIteration is raised and we know the whole iterable contains just the one value. 如果没有这样的元素,则会引发StopIteration ,并且我们知道整个可迭代对象仅包含一个值。 If no StopIteration was raised we found evidence it wasn't unique. 如果没有引发StopIteration ,我们会发现它不是唯一的证据。

It'll also return True if there are no elements in it at all. 如果根本没有元素, it也会返回True

Demo: 演示:

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

For very long lists, it is not efficient to build a complete set as you are able to abort as soon as a "non-match" is encountered. 对于非常长的列表,构建完整的集合效率不高,因为一旦遇到“不匹配”,您就可以中止。 In that case, a plain old imperative loop is to be considered: 在这种情况下,应考虑一个普通的旧式命令式循环:

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