如果我在python中有2个变量的列表,如何根据列表中的出现对它们进行排序

时间:2018-03-24 04:57:34

标签: python python-3.x list arraylist

因此软件从用户那里获取输入 并将它们打印为数组。 如果该值不会多次出现,则不会打印它

 # for example I had these inputs by the users
 Z=[(2,40),(1,15),(3,9),(2,12),(1,15),(3,9),(1,15)]        

 # so that output should be
 1 15

 3 9

2 个答案:

答案 0 :(得分:1)

使用Counter之类的:

from collections import Counter

Z=[(2,40),(1,15),(3,9),(2,12),(1,15),(3,9),(1,15)]
x = Counter(Z)
print ([k for k, v in x.items() if v > 1])

结果:

[(1, 15), (3, 9)]

答案 1 :(得分:0)

您可以使用collections.Counter获取出现次数,然后将其用作按项目出现在列表中的次数递减顺序排序的键。

from collections import Counter

def sort_by_occurence(lst, min_occurence=1):
    counter = Counter(lst)
    occ = (k for k, v in counter.items() if v >= min_occurence)
    return sorted(occ, key=lambda e: counter[e], reverse=True)

z = [(2, 40), (1, 15), (3, 9), (2, 12), (1, 15), (3, 9), (1, 15)]
sort_by_occurence(z, min_occurence=2) # [(1, 15), (3, 9)]