【python cookbook】找出序列中出現次數最多的元素


 

問題

《Python Cookbook》中有這么一個問題,給定一個序列,找出該序列出現次數最多的元素。
例如:

words = [
   'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
   'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
   'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
   'my', 'eyes', "you're", 'under'
]

統計出words中出現次數最多的元素?

初步探討

1、collections模塊的Counter類
首先想到的是collections模塊的Counter類,具體用法看這里!具體用法看這里!具體用法看這里!https://docs.python.org/3.6/l...,重要的事情強調三遍。

from collections import Counter

words = [
   'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
   'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
   'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
   'my', 'eyes', "you're", 'under'
]

counter_words = Counter(words)
print(counter_words)
most_counter = counter_words.most_common(1)
print(most_counter)

關於most_common([n]):

2、根據dict鍵值唯一性和sorted()函數

import operator

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]

dict_num = {}
for item in words:
    if item not in dict_num.keys():
        dict_num[item] = words.count(item)
        
# print(dict_num)

most_counter = sorted(dict_num.items(),key=lambda x: x[1],reverse=True)[0]  
print(most_counter)    

sorted函數:
傳送門:https://docs.python.org/3.6/l...

iterable:可迭代類型;
key:用列表元素的某個屬性或函數進行作為關鍵字,有默認值,迭代集合中的一項;
reverse:排序規則. reverse = True 降序 或者 reverse = False 升序,有默認值。
返回值:是一個經過排序的可迭代類型,與iterable一樣。

這里,我們使用匿名函數key=lambda x: x[1]
等同於:

def key(x):
    return x[1]

這里,我們利用每個元素出現的次數進行降序排序,得到的結果的第一項就是出現元素最多的項。

更進一步

這里給出的序列很簡單,元素的數目很少,但是有時候,我們的列表中可能存在上百萬上千萬個元素,那么在這種情況下,不同的解決方案是不是效率就會有很大差別了呢?
為了驗證這個問題,我們來生成一個隨機數列表,元素個數為一百萬個。
這里使用numpy Package,使用前,我們需要安裝該包,numpy包下載地址:https://pypi.python.org/pypi/...。這里我們環境是centos7,選擇numpy-1.14.2.zip (md5, pgp)進行下載安裝,解壓后python setup.py install

 

def generate_data(num=1000000):
    return np.random.randint(num / 10, size=num)

np.random.randint(low[, high, size]) 返回隨機的整數,位於半開區間 [low, high)
具體用法參考https://pypi.python.org/pypi

OK,數據生成了,讓我們來測試一下兩個方法所消耗的時間,統計時間,我們用time函數就可以。

 

#!/usr/bin/python
# coding=utf-8
#
# File: most_elements.py
# Author: ralap
# Data: 2018-4-5
# Description: find most elements in list
#

from collections import Counter
import operator
import numpy as np
import random
import time


def generate_data(num=1000000):
    return np.random.randint(num / 10, size=num)


def collect(test_list):
    counter_words = Counter(test_list)
    print(counter_words)
    most_counter = counter_words.most_common(1)
    print(most_counter)


def list_to_dict(test_list):
    dict_num = {}
    for item in test_list:
        if item not in dict_num.keys():
            dict_num[item] = test_list.count(item)

    most_counter = sorted(dict_num.items(), key=lambda x: x[1], reverse=True)[0]
    print(most_counter)

if __name__ == "__main__":
    list_value = list(generate_data())

    t1 = time.time()
    collect(list_value)
    t2 = time.time()
    print("collect took: %sms" % (t2 - t1))

    t1 = t2
    list_to_dict(list_value)
    t2 = time.time()
    print("list_to_dict took: %sms" % (t2 - t1))

以下結果是我在自己本地電腦運行結果,主要是對比兩個方法相對消耗時間。

 

當數據比較大時,消耗時間差異竟然如此之大!下一步會進一步研究Counter的實現方式,看看究竟是什么魔法讓他性能如此好。

參考資料

https://blog.csdn.net/xie_0723/article/details/51692806

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM