Python 在相同位置具有相同长度的多个列表之间查找匹配项

Python 在相同位置具有相同长度的多个列表之间查找匹配项,python,Python,我有两个列表(稍后可能会有更多),我想找出在同一位置的马赫值。 下面的代码返回匹配的值,但不返回匹配的位置 a = [5,0] b = [5,1] print list(set(a).intersection(set(b))) >>5 您可以编写自己的方法: a = [1, 2, 3, 4, 5] b = [5, 4, 3, 2, 1] c = [3, 3, 3, 3, 3] allLists = [b, c] # all lists but the first for i

我有两个列表(稍后可能会有更多),我想找出在同一位置的马赫值。

下面的代码返回匹配的值,但不返回匹配的位置

a = [5,0]
b = [5,1]

print list(set(a).intersection(set(b)))

>>5

您可以编写自己的方法:

a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
c = [3, 3, 3, 3, 3]
allLists = [b, c] # all lists but the first

for i in range(len(a)):
    good = True
    for l in allLists:
        if l[i] != a[i]:
            good = False
            break
    if good:
        print(i, a[i])

编辑后可以更轻松地添加更多列表

使用
zip
枚举
并检查唯一值:

lists = [a, b] # add more lists here if need be...
for idx, items in enumerate(zip(*lists)):
    unique = set(items)
    if len(unique) == 1:
        # idx = position, unique.pop() == the value
        print idx, unique.pop()

可以使用。一个简单的列表理解来测试A、b和c的每个单独值。可以为要比较的每个列表添加或多或少的
=
。但是,这假设所有列表的长度相同,或者a是最短的列表。

这将显示匹配的位置(假设值None不是有效元素)

或者,如果您想保持每个位置的匹配:

matches=[reduce(lambda x, y: x if x == y else None, i) for i in z]
会产生

[None, 2, None]

这是您想要使用的任意多个列表的答案

a = [5,0,1,2]
b = [5,2,3,2]
lists = [a,b,b,a,a]
d = dict()
for l in lists:
    for i in range(len(a)):
        if i not in d.keys():
            d[i] = a[i]
        elif d[i] != l[i]:
            d[i] = -1
for i in d.keys():
    if d[i] != -1:
        print d[i], i

因此,如果有3个列表,那么所有列表都必须在相同的位置匹配?是否每个列表都保证具有相同的长度?jep Gauranted需要具有相同的长度,是的,Jon您必须始终再添加一个列表,到if语句。这里的*是什么?它被称为unpacking-它允许使用
列表中指定的可变数量的参数调用zip函数-有关完整信息,请参阅。*允许可变数量的参数。允许向函数中传递所需的任意多个列表。此解决方案的优点在于,它可以轻松处理列表长度不尽相同的情况。@steve yup-它将自动在最短的列表上停止。。。当然
izip_longest
如果不应该的话也可以使用……当我必须添加更多列表时,我必须始终更改代码。你测试过你的代码吗?添加更多列表时,不再有匹配项。每当我想添加更多列表时,必须更改代码。我喜欢
check_equal
-在列表元素不可散列的情况下检查唯一性的简明方法
[None, 2, None]
a = [5,0,1,2]
b = [5,2,3,2]
lists = [a,b,b,a,a]
d = dict()
for l in lists:
    for i in range(len(a)):
        if i not in d.keys():
            d[i] = a[i]
        elif d[i] != l[i]:
            d[i] = -1
for i in d.keys():
    if d[i] != -1:
        print d[i], i
def check_equal(lst):
   return lst[1:] == lst[:-1]

def get_position_and_matches(*lists):
  shortest_list = min(lists, key=len)
  for index,item in enumerate(shortest_list):
    matching = [l[index] for l in lists]
    if check_equal(matching):
      print "Index: {0}, Value: {1}".format(index, shortest_list[index])

one = [1, 3, 4, 6, 2]
two = [1, 3, 4, 2, 9, 9]
three = [2, 3, 4]
get_position_and_matches(one, two, three)