获取多个列表共有的字符串元素的索引

1 python

我想获得多个列表共有的字符串元素的索引.只有'狗'和'斑马'分别对于两个(A和B)和三个列表(A,B和C)是共同的.

A = ['apple','banana','dog','fig','zebra']
B = ['zebra','avocado','dog','egg','corn']
C = ['egg','guava','zebra','carrot','beans']
Run Code Online (Sandbox Code Playgroud)

预期的答案是:

A[2] A[4] B[0] B[2] B[3] C[0] C[2]
Run Code Online (Sandbox Code Playgroud)

我想用干净简单的方法来实现它.

Gra*_*ntJ 5

使用collections.Counter数据类型实际上更有效.计数器就像一个字典,但可以计算给它的项目作为输入.你会像这样使用它:

A = ['apple','banana','dog','fig','zebra']
B = ['zebra','avocado','dog','egg','corn']
C = ['egg','guava','zebra','carrot','beans']

from collections import Counter
counts = Counter()

for values in [A, B, C]:
    # Assumes `values` are unique in each of A, B, C
    # If not, then convert `values` to a set first.
    counts.update(values)

for name, values in [('A', A), ('B', B), ('C', C)]:
    for index, item in enumerate(values):
        if counts[item] > 1:
            print '{0}[{1}]'.format(name, index),

# Output:
# A[2] A[4] B[0] B[2] B[3] C[0] C[2]
Run Code Online (Sandbox Code Playgroud)

通过使用计数器,列表中的项目将按线性时间进行处理.稍后查找计数也会在线性时间内进行.所以整个程序运行得很快.

相比之下,接受的答案在二次时间内起作用,如果您的列表中有数千个元素,则会很慢.