文章目录
- 1. 解压赋值给多个变量
- 2. 解压可迭代对象赋值给多个变量
- 3. 查找集合中最大/最小的N个元素-heap
- 4. 处理字典中的多值映射的两种方式-defaultdict()
- 5. 排序字典的键值对元素-OreredDict
- 6. 查找字典的相同点
- 7. 命名切片-slice()
- 8. 计算序列中出现次数最多的元素-Counter
- 9. 按关键字排序字典列表-itemgetter()
- 10. 提取字典中的子集
- 11. 合并字典-update()
最近在看Python cookbook, 总结下书中的涉及部分比较骚的操作用例。仅作分享。
1. 解压赋值给多个变量
p = (4, 5)
x, y = p
print(x, y)
data = ['ACMDE', 50, 9.11, (2012, 8, 3)]
name, shares, price, date = data
print(name, shares, price, date)
name, shares,price,(year,mon,day) = data
print(year, mon, day)
s = 'Hello'
a, b, c, d, e=s
print('字符串解压:', a, b, c, d, e)
_, shares, price, _ = data
print('部分解压:',shares, price)
2. 解压可迭代对象赋值给多个变量
场景1:被解压元素不确定 - 星号表达式
场景2:利用废弃名称 _ 或ign , 丢弃被解压的元素 -
record = ['Dave', 'Dave@gmail.com', '027-83912629', '027-91820129']
name, email, *phones = record
print(name, email, phones)
*before, current = [10, 8, 7, 9, 6]
avg1 = sum(before)/len(before)
print('前6个月的平均值:{},当前月值为:{}, 占比是:{}'.format(avg1, current, avg1/current))
3. 查找集合中最大/最小的N个元素-heap
heap模块的nlargest(), nsmallest()
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 47, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
portfolio = [
{'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}
]
print('\n 字典')
print(heapq.nlargest(3, portfolio, key=lambda s:s['price']))
heapq,底层实现里会将集合数据进行堆排序会放入一个列表
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 47, 2]
import heapq
heapq.heapify(nums)
print('\n经过堆排序后的结果集:', nums)
4. 处理字典中的多值映射的两种方式-defaultdict()
defaultdict 类, 只需要关注元素的添加操作
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
d_s = defaultdict(set)
d_s['a'].add(1)
d_s['a'].add(2)
d_s['b'].add(4)
d = {}
for key, value in pairs:
if key not in d:
d[key] = []
d[key].append(value)
5. 排序字典的键值对元素-OreredDict
向字典中添加键值对时,元素是无序存储的。collections 模块的 OrderedDict类可以改变这种默认规则
from collections import OrderedDict
def ordered_dict():
d=OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
for key in d:
print(key, d[key])
ordered_dict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
import json
json.dumps(d)
6. 查找字典的相同点
a = { 'x' : 1, 'y' : 2, 'z' : 3 }
b = { 'w' : 10, 'x' : 11, 'y' : 2 }
print(a.keys() & b.keys() )
print(a.keys() - b.keys() )
print('(键-值)元素对:',a.items() & b.items())
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
print(c)
7. 命名切片-slice()
利用slice()来命名切片,提高可读性高。
record = '....................100 .......513.25 ..........'
SHARES = slice(20, 23)
PRICE = slice(31, 37)
cost = int(record[SHARES]) * float(record[PRICE])
8. 计算序列中出现次数最多的元素-Counter
collections.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' ]
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
9. 按关键字排序字典列表-itemgetter()
itemgetter.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} ]
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
print(rows_by_fname)
print(rows_by_uid)
rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
rows_by_lfname = sorted(rows, key=lambda r: (r['lname'],r['fname']))
print(rows_by_lfname)
10. 提取字典中的子集
prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 }
p1 = {key: value for key, value in prices.items() if value > 200}
tech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' }
p2 = { key:prices[key]
for key in prices.keys() & tech_names }
11. 合并字典-update()
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
from collections import ChainMap
c = ChainMap(a, b)
print(c)
a['x'] = 42
print('修改源字典值后, 结果会跟着改变:', c)
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
merged=dict(b)
merged.update(a)
print('udpate()之前的字典为:', merged)
a['x'] = 39
print('修改源字典后,update()的对象并没有改变:', merged)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)