【Python】巧借模块完成信息处理小技巧整理

找出列表或字典中最大或最小的元素

import heapq
list1 = [34, 2, 5, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
    {
    
    'name': 'IBM', 'shares': 100, 'price': 91.1},
    {
    
    'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {
    
    'name': 'FB', 'shares': 200, 'price': 21.09},
    {
    
    'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {
    
    'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {
    
    'name': 'ACME', 'shares': 75, 'price': 115.65}
]
# 取出列表中从大到小排列的前3个数
print(heapq.nlargest(3, list1))
# 取出列表中从小到大排列的前3个数
print(heapq.nsmallest(3, list1))
# 取出字典中,以key对应的值作为排列依据,最大的2个数
print(heapq.nlargest(2, list2, key=lambda x: x['price']))
print(heapq.nlargest(2, list2, key=lambda x: x['shares']))

找出列表中出现次数最多的元素

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 = Counter(words)
# 打印出现次数最多的3个元素,同时打印出现的次数
print(counter.most_common(3))

猜你喜欢

转载自blog.csdn.net/Nicky_Zheng/article/details/109012092
今日推荐