在多个列表中查找匹配元素的交集并返回索引

时间:2013-06-14 21:13:19

标签: python

所以我的一个程序出了问题。我有几个列表,它们的长度都相同。列表是原始列表的组合。我需要的是一个特定元素重复多次的索引。例如:

a = ["x","t","y"]
b = ["t","x","y"]
c = ["t","t","y"]

我希望它变成2.

4 个答案:

答案 0 :(得分:1)

让你入门的东西:

In [7]: for i, n in enumerate(zip(a,b,c)): print n, i
('x', 't', 't') 0
('t', 'x', 't') 1
('y', 'y', 'y') 2

答案 1 :(得分:1)

map(lambda x: x.count(x[0]) == len(x), zip(*[a, b, c])).index(True)

x.count(x[0]) == len(x)len(set(x)) == 1

快得多

对于较大的子列表> 20个元素lambda x: x == len(x)*[x[0]]甚至更快:

答案 2 :(得分:0)

我认为你正在寻找这样的东西:

>>> a = ["x","t","y"]
>>> b = ["t","x","y"]
>>> c = ["t","t","y"]
>>> lis = [a, b, c]
>>> next( i for i,x in enumerate(zip(*lis)) if len(set(x)) == 1)
2

zip(*lis)解压缩列表并获得:

>>> lis = [a, b, c]
>>> zip(*lis)
[('x', 't', 't'), ('t', 'x', 't'), ('y', 'y', 'y')]

现在我们可以迭代这个新列表的每个项目,并检查所有项目相同的索引。 set是检查该内容的最佳方式。

>>> set(('y', 'y', 'y'))
set(['y'])               #length is 1

答案 3 :(得分:0)

单行:

filter(lambda x : a[x] == b[x] and a[x] == c[x], range(len(a)))

请注意,这将返回包含所有元素匹配的索引的列表,因此您实际上会得到[2],而不是2

如果您只想要整数值(不是列表):

idxs = filter(lambda x : a[x] == b[x] and a[x] == c[x], range(len(a)))
result = idxs[0] if idxs else None