在Python中,如何比较两个列表并获取匹配的所有索引?

时间:2011-02-08 19:51:36

标签: python

这可能是一个简单的问题,我只是缺少但是我有两个包含字符串的列表,我想逐个元素地“反弹”一个,而另一个返回匹配的索引。我希望有多个匹配,并希望所有的指数。我知道list.index()获得第一个,你可以很容易地得到最后一个。例如:

list1 = ['AS144','401M','31TP01']

list2 = ['HDE342','114','M9553','AS144','AS144','401M']

然后我将遍历list1,比较list2并输出:
第一次迭代的[0,0,0,1,1,0] , [3,4]或等等 第二个[0,0,0,0,0,1] , [6] 和第三次[0,0,0,0,0,0][]

编辑: 对不起任何困惑。我希望以某种方式获得结果,然后我可以像这样使用它们 - 我有第三个列表可以调用list3,我想从输出的索引中获取该列表中的值。即list3[previousindexoutput]=list of cooresponding values

7 个答案:

答案 0 :(得分:9)

就我个人而言:

matches = [item for item in list1 if item in list2]

答案 1 :(得分:3)

这不回答这个问题。请参阅下面的评论。

首先:

list(i[0] == i[1] for i in zip(list1, list2))

答案 2 :(得分:1)

我不确定你希望如何将这些打包起来,但是这样做了:

def matches(lst, value):
    return [l == value for l in lst]

all_matches = [matches(list2, v) for l in list1]

答案 3 :(得分:1)

[([int(item1 == item2) for item2 in list2], [n for n, item2 in enumerate(list2) if item1 == item2]) for item1 in list1]

答案 4 :(得分:1)

def findInstances(list1, list2):
    """For each item in list1,
    return a list of offsets to its occurences in list2
    """

    for i in list1:
        yield [pos for pos,j in enumerate(list2) if i==j]

list1 = ['AS144','401M','31TP01']
list2 = ['HDE342','114','M9553','AS144','AS144','401M']

res = list(findInstances(list1, list2))

结果

[[3, 4], [5], []]

答案 5 :(得分:0)

这将给出一个列表,列出True / False值而不是1/0:

matches = [ [ list1[i] == list2[j] for j in range(0, len(list2)) ] for i in range(0, len(list1)) ]

编辑:如果您使用的是2.5或更高版本,那么这应该是1& 0的:

matches = [ [ 1 if list1[i] == list2[j] else 0 for j in range(0, len(list2)) ] for i in range(0, len(list1)) ]

答案 6 :(得分:0)

这应该做你想要的,它可以很容易地变成一个发电机:

>>> [[i for i in range(len(list2)) if item1 == list2[i]] for item1 in list1]
[[3, 4], [5], []]

这是一个输出格式略有不同的版本:

>>> [(i, j) for i in range(len(list1)) for j in range(len(list2)) if list1[i] == list2[j]]
[(0, 3), (0, 4), (1, 5)]
相关问题