python統計列表元素重複次數的N中方法
阿新 • • 發佈:2019-02-15
一個列表peopleidlistall裡面有好幾萬個元素,我想找到裡面重複元素的次數,或者說找到重複元素次數為length的元素。
第一種,python的list自帶的count方法:
peopleidlistall2 = list(set(peopleidlistall)) id_peoplelist = list() for id_people in peopleidlistall2: times = peopleidlistall.count(id_people) if times == length: id_peoplelist.append(id_people)
此時的id_peoplelist便是重複次數為length的元素的集合。
第二種,使用字典的迭代器方法,使用的iterkeys方法:
peopleiddict = dict(Counter(peopleidlistall)) id_peoplelist = list() for id_p in peopleiddict.iterkeys(): #print id_p, peopleiddict[id_p] if peopleiddict[id_p] == length: #print peopleiddict[id_p] id_peoplelist.append(id_p)
此時的id_peoplelist便是重複次數為length的元素的集合。
第三種,使用字典的傳統方法,也是使用for迴圈:
peopleiddict = dict(Counter(peopleidlistall))
id_peoplelist = list()
for i in range(len(peopleiddict)):
if peoplelist[i][1] == length:
id_peoplelist.append(peoplelist[i][0])
此時的id_peoplelist便是重複次數為length的元素的集合。
使用字典的values方法:
peopleiddict = dict(Counter(peopleidlistall))
id_peoplelist = list()
for i in range(len(peopleiddict.values())):
if peopleiddict.values()[i] == 2:
id_peoplelist.append(peopleiddict.keys()[i])
此時的id_peoplelist便是重複次數為length的元素的集合。
我推薦第二種迭代的方式,據說是效率要搞很多,但是我沒有測試過。