如何比较列表中的相应位置?

时间:2014-05-04 03:55:46

标签: python python-2.7

我有N个相同长度的列表。如何在相应位置比较这些列表并输出它们全部匹配的位置数?

例如:

A=[1,0,1,1]
B=[1,1,1,1]
C=[1,0,1,0]

这三个列表的比较将输出2,因为只有位置1和3匹配。

我正在考虑将其转换为元组,然后将其压缩K=zip(A,B,C),然后添加每个元组以查看它是否与列表的数量匹配。

问题几乎听起来像是我错过了一些相当微不足道的东西,也许!

4 个答案:

答案 0 :(得分:4)

sum(1 if x == y == z else 0 for x, y, z in zip(A, B, C))
2

答案 1 :(得分:3)

>>> A = [1, 0, 1, 1]
>>> B = [1, 1, 1, 1]
>>> C = [1, 0, 1, 0]
>>> [len(set(i)) == 1 for i in zip(A,B,C)]
[True, False, True, False]

>>> sum(len(set(i))==1 for i in zip(A,B,C))
2

答案 2 :(得分:0)

使用set,就像在gnibbler的答案中一样,适用于包含任何不可变元素的列表 - 任意整数,浮点数,字符串,元组。 OP的问题并没有对列表可能包含的内容施加任何限制,并假设只有0和1不能简化任何事情。以下内容也适用于任意数量的列表,而不仅仅是3, 似乎是OP要求的一部分。

A=[1,0,1,1, 'cat', 4.5,     'no']
B=[1,1,1,1, 'cat', False,   'no']
C=[1,0,1,0, 16,    'John',  'no']
D=[1,0,0,0, (4,3), 'Sally', 'no']


def number_of_matching_positions(*lists):
    """
    Given lists, a list of lists whose members are all of the same length,
    return the number of positions where all items in member lists are equal.
    """
    return sum([len(set(t)) <= 1 for t in zip(* lists)])

print(number_of_matching_positions(),
      number_of_matching_positions(A),
      number_of_matching_positions(A, A),
      number_of_matching_positions(A, B),
      number_of_matching_positions(A, B, C),
      number_of_matching_positions(A, B, C, D))

这将打印0 7 7 5 3 2

如果列表N的数量可能很大,可以通过检查zip中每个元组的尽可能少的元素来提高性能:

def all_equal(t):
    """Return True if all elements of the sequence t are equal, False otherwise."""
    # Use a generator comprehension,
    # so that 'all' will stop checking t[i] == t[0] 
    # as soon as it's false for some i.
    return (not t) or \
            all( (t[i] == t[0] for i in range(1, len(t))) )

def number_of_matching_positions_alt(*lists):
    # Instead of 'len(set(t)) <= 1', 
    # do less work in case len(lists) alias len(t) can be large
    return sum( [all_equal(t) for t in zip(* lists)] )

答案 3 :(得分:0)

如果您想知道所有列表匹配的位置,那么

list(x for x, (xa, xb, xc) in enumerate(zip(a, b, c))
     if xa == xb == xc)

在我看来是最可读的方式

如果您只想计算列数

sum(xa == xb == xc for xa, xb, xc in zip(a, b, c))

这要归功于Python TrueFalse可以在计算中使用,就像它们是10一样。

相关问题