python cookbook笔记第二弹

1.11-1.20

第一章数据结构后半段

# 命名切片,避免大量无法理解的下标
# 考虑从多条记录中读取数据(一条记录内容如下)
record = '....................100 .......513.25 ..........'
cost = int(record[20:23]) * float(record[31:37])
# 很久之后,cost的含义难以理解
SHARES = slice(20, 23)
PRICE = slice(31, 37)
cost = int(record[SHARES]) * float(record[PRICE])
cost
# 同样可以进行删除,赋值等操作
record = list(record)
record[SHARES] = ['2', '0', '0']
del record[PRICE]
record
# 可以调用start,stop,step属性查看命名切片的性质
a = slice(2, 50, 2)
a.start
a.stop
a.step
# 调用indices方法映射到指定序列
s = [2, 3, 4, 5, 6, 7, 8, 9, 0]
a.indices(len(s))
for i in range(*a.indices(len(s))):
  print(s[i])

# 如何求出一个序列中出现次数最多的元素?
# 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)
word_counts['eyes']
morewords = ['why','are','you','not','looking','in','my','eyes']
word_counts.update(morewords)
word_counts['eyes']

# 列表推导&生成器表达式
mylist = [1, 4, 5, -6, -7, -8, 9, 4, 3, 0]
[n for n in mylist if n > 0]
[n for n in mylist if n < 0]
# 列表推导的缺点:当存在大量数据时,非常消耗内存
# 因此可以考虑使用生成器表达式
pos = (n for n in mylist if n > 0)
for x in pos:
  print(x)

# 当过滤条件复杂,可以考虑构建一个函数,同时结合内置的filter()使用
values = ['1', '2', '-3', '-', '4', 'N/A', '5']
def is_int(val):
  try:
    x = int(val)
    return True
  except ValueError:
    return False
ivals = list(filter(is_int, values))
ivals

# 当然也可以一边过滤一边转换
import math
mylist = [1, 2, -4, -5, -9, 0]
[math.sqrt(n) if n > 0 else n ** 2 for n in mylist]
# compress过滤器
# 根据bool输出对应位True的元素
cut = [n > 0 for n in mylist]
cut
from itertools import compress
list(compress(mylist, cut))

# 从字典中提取子集
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}
p1

# 命名元组,避免下标,提高代码可读性
# 考虑你有一个股票的记录records
# 组成成分是一个字符串,代表名字,两个数字分别表示份额和单价
# 现在希望对他们求和
records = [
    ['zhang', 100, 923.5],
    ['zhao', 200, 999.9],
    ['qian', 40, 900.8],
    ['king', 199, 986.9]
]
# 普通的代码如下
total = 0
for item in records:
  total += item[1] * item[2]
total
# 这是数据比较简单,如果增加几列,下标看起来就非常让人不愉快
# 于是,我们考虑引入具名元组
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
total = 0
for item in records:
  # print(*item)
  # *item 表示列表中的所有元素
  rec = Stock(*item)
  total += rec.shares * rec.price
total
# 具名元组具有元组的属性,可以拆包,len()等操作,同时不能直接修改
# 但是可以通过_replace()方法改动
s = Stock('ACME', 100, 123.45)
s = s._replace(shares=75)
s

# 合并多个字典或者映射
# 现在假设你必须在两个字典中执行查找操作(比如先从 a 中找,如果找不到再在 b
# 中找)。一个非常简单的解决方案就是使用 collections 模块中的 ChainMap 类。
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
from collections import ChainMap
c = ChainMap(a, b)
print(c['z'])
# 结果是3,因为先在a中找
c['x']

全部更新完咯!下周开始看第二章辣

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值