如何在某些元素列表中找到列表中最频繁出现的位置?

时间:2020-08-05 13:45:29

标签: python algorithm sorting frequency-distribution

例如,有一个元素列表

[8,6,3,7,1,8,8,9,2,0,5,4,7,9,2,8,2,5,5,6,3,0,1,7,9,2,9,6,7,0,5,2,7,4,5,6,2,1,9,0,3,1,3,9,4,9,2,7,5,9,0,5,2,1,8,6,4]

我试图在上面的列表中查找位置(索引),以找到第二个匹配项

[1,4,3,8]

enter image description here

有通用且优雅的算法吗?

1 个答案:

答案 0 :(得分:1)

这里是使用绘图的简单视觉表示:

import matplotlib.pyplot as plt

lst = [8,6,3,7,1,8,8,9,2,0,5,4,7,9,2,8,2,5,5,6,3,0,1,7,9,2,9,6,7,0,5,2,7,4,5,6,2,1,9,0,3,1,3,9,4,9,2,7,5,9,0,5,2,1,8,6,4]
target = [1,4,3,8]
result = [0]*len(lst)

for i in range(len(lst)):
    if lst[i] in target:
        result[i] = 1

plt.step(range(len(lst)), result)
plt.show()

给出以下相当容易分析的结果:

enter image description here

x轴表示列表中的索引,1表示目标列表,0表示不在列表中。