1、從序列中移除重復(fù)項(xiàng)且保持元素間順序不變
# coding=utf-8
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item # 可以使函數(shù)可迭代
seen.add(item)
a = [1, 5, 2, 1, 9, 1, 5, 10]
print(list(dedupe(a)))
>>[1, 5, 2, 9, 10]
2、找出序列中出現(xiàn)次數(shù)最多的元素
collections模塊中的Counter類正是為此類問題所設(shè)計(jì)的。它甚至有一個非常方便的most_common()方法可以直接告訴我們答案。
# coding=utf-8
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'
]
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
3、通過公共鍵對字典列表排序
利用operator模塊中的itemgetter函數(shù)對這類結(jié)構(gòu)進(jìn)行排序是非常簡單的實(shí)現(xiàn)對公共鍵對字典列表排序。
# coding=utf-8
from operator import itemgetter
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
4、將名稱映射到序列的元素中
相比普通的元組,collections.namedtuple()(具名元組)只增加了極小的開銷就提供了這些便利。實(shí)際上collections.namedtuple()是一個工廠方法,它返回的是Python中標(biāo)準(zhǔn)元組類型的子類。我們提供給它一個類型名稱以及相應(yīng)的字段,它就返回一個可實(shí)例化的類、為你已經(jīng)定義好的字段傳入值等。
# coding=utf-8
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
def compute_cost(records):
total = 0.0
for rec in records:
s = Stock(*rec)
total += s.shares * s.price
return total
records = [['apple', 0.4, 5], ['banana', 0.6, 3]]
result = compute_cost(records)
5、將多個映射合并為單個映射
一種簡單的方法是利用collections模塊中的ChainMap類來解決這個問題。
# coding=utf-8
from collections import ChainMap
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
c = ChainMap(a,b)
print(c['x']) # Outputs 1 (from a)
print(c['y']) # Outputs 2 (from b)
print(c['z']) # Outputs 3 (from a)
如果有重復(fù)的鍵,那么這里會采用第一個映射中所對應(yīng)的值。因此,例子中的c[‘z’]總是引用字典a中的值,而不是字典b中的值。