我想获取多个列表共有的字符串元素的索引。 只有“狗”和“斑马”分别对两个列表(A 和 B)和三个列表(A、B 和 C)是公共(public)的。
A = ['apple','banana','dog','fig','zebra']
B = ['zebra','avocado','dog','egg','corn']
C = ['egg','guava','zebra','carrot','beans']
预期的答案是:
A[2] A[4] B[0] B[2] B[3] C[0] C[2]
我想用干净简单的方式完成它。
最佳答案
实际上使用 collections.Counter 数据类型更有效。 Counter 的工作方式类似于 dict,但可以计算作为输入提供给它的项目。你会像这样使用它:
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]
通过使用计数器,列表中的项目以线性时间处理。稍后对计数的查找也在线性时间内发生。所以整个程序运行得非常快。
相比之下,接受的答案在二次时间内有效,如果列表中有数千个元素,速度会非常慢。
关于python - 获取多个列表共有的字符串元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23901946/