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

0 投票
2 回答
3190 浏览
提问于 2025-04-18 21:17

我想检查一下,在一组元组中,第二个元素是否都是相同的。

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

2 个回答

1

对于非常长的列表,构建一个完整的集合并不高效,因为一旦遇到一个“不匹配”的项,你就可以立即停止。在这种情况下,可以考虑使用一个普通的循环:

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

你把事情搞得太复杂了。其实你只需要一个集合,然后检查这个集合里是否只有一个元素:

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

撰写回答