python笔记(一)

模式匹配

import re
match = re.match('Hello[ \t]*(.*)world','Hello	Python world')
match.group(1)
out:'Python'
match = re.match('/(.*)/(.*)/(.*)','/usr/home/lumberjack')
match.groups()
out:('usr','home','lumberjack')

列表

序列操作

>>> L = [123, 'spam', 1.23]
>>> len(L)
3
>>> L[0]
123
>>> L[:-1]
[123, 'spam']
>>> L + [4, 5, 6]
[123, 'spam', 1.23, 4, 5, 6]
>>> L
[123, 'spam', 1.23]		# We're not changing the original list
>>> L.append('NI')
>>> L
[123, 'spam', 1.23, 'NI']
>>> L.pop(2)
1.23
>>> L
[123, 'spam', 'NI']

其他的列表方法可以在任意位置插入(insert)元素, 按照值移除(remove)元素等.

>>> M = ['bb', 'aa', 'cc']
>>> M.sort()
>>> M
['aa', 'bb', 'cc']
>>> M.reverse()
>>> M
['cc', 'bb', 'aa']

嵌套

>>> M = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

列表解析

矩阵是按照行进行存储的

>>> col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[1] + 1 for row in M]
[3, 6, 9]
>>> [row[1] for row in M if row[1] % 2 == 0]
[2, 8]
>>> diag = [M[i][i] for i in [0, 1, 2]]
>>> diag
[1, 5, 9]

>>> doubles = [c * 2 for c in 'spam']
>>> doubles
['ss', 'pp', 'aa', 'mm']

括号中的解析语法也可以用来创建产生所需要结果的生成器

>>> G = (sum(row) for row in M)
>>> next(G)
6
>>> next(G)
15

内置函数map可以做类似的事情, 产生对各项运行一个函数的结果, 将其包装到列表中, 会使其返回所有值

>>> list(map(sum, M))
[6, 15, 24]

解析语法也可以用来创建集合和字典

>>> {sum(row) for row in M}
{24, 6, 15}
>>> {i: sum(M[i]) for i in range(3)}
{0: 6, 1: 15, 2: 24}
>>> [ord(x) for x in 'spaam']
[115, 112, 97, 97, 109]
>>> {ord(x) for x in 'spaam'}
{112, 97, 115, 109}
>>> {x: ord(x) for x in 'spaam'}
{'a': 97, 'p': 112, 's': 115, 'm': 109}

字典

字典是python核心对象集合中的唯一的一种映射类型, 也具有可变性

字典的元素要按某种顺序进行输出, 常用的解决方法就是通过字典的keys方法收集一个键的列表, 使用列表的sort方法进行排序.

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> Ks = list(D.keys())
>>> Ks.sort()
>>> Ks
['a', 'b', 'c']
>>> for key in Ks:
    	print(key, '=>', D[key])
a => 1
b => 2
c => 3

不存在的键: if测试

>>> D = {'a': 1, 'c': 3, 'b': 2}
>>> D['e'] = 99
>>> D
 {'a': 1, 'c': 3, 'b': 2, 'e': 99}
>>> if not 'f' in D:
    	print('missing')
missing

有其他的方法来创建字典并避免获取不存在的字典键: get方法(带有一个默认值的条件索引)

>>> value = D.get('x', 0)
>>> value
0
>>> value = D['x'] if 'x' in D else 0
>>> value
0

元组

元组对象基本上就像一个不可以改变的列表, 不能增长或缩短

>>> T = (1, 2, 3, 4)
>>> len(T)
4
>>> T + (5, 6)
(1, 2, 3, 4, 5, 6)
>>> T[0]
1

>>> T.index(4)		# Tuple methods: 4 appears at offset 3
3
>>> T.count(4)		# 4 appears once
1

元组支持混合的类型和嵌套, 但是不能增长或缩短, 因为它们是不可变的

>>> T = ('spam', 3.0, [11, 22, 33])
>>> T[1]
3.0
>>> T[2][1]
22
>>> T.append(4)
AttributeError: 'tuple' object has no attribute 'append'

文件

要创建一个文件对象, 需要调用内置的open函数, 以字符串的形式传递给它一个外部的文件名以及一个处理模式的字符串.

>>> f = open('data.txt', 'w')
>>> f.write('Hello\n')		# Write strings of bytes to it
6
>>> f.write('world\n')		# Returns number of bytes written in Python3.0
f.close

>>> f = open('data.txt')
>>> text = f.read()
>>> text
'Hello\nworld\n'

>>> print(text)
Hello
world

>>> text.split()
['Hello', 'world']

文本文件把内容显示为字符串, 并且自动执行Unicode编码和解码, 而二进制文件把内容显示为一个特定的字节字符类型, 并且允许你不修改的访问文件内容.

data = open('data.bin', 'rb').read()	# Open binary file
>>> data
b'\x00\x00\x00\x07spam\x00\x08'
>>> data[4:8]
b'spam'

集合

>>> X = set('spam')
>>> Y = {'h', 'a', 'm'}
>>> X, Y
{'a', 'p', 's', 'm'}, {'a', 'h', 'm'}
>>> X & Y
{'a', 'm'}
>>> X | Y
{'a', 'p', 's', 'h', 'm'}
>>> X - Y
{'p', 's'}
>>> {x ** 2 for x in [1, 2, 3, 4]}
{16, 1, 4, 9}

固定精度浮点数及分数

>>> import decimal
>>> d = decimal.Decimal('3.141')
>>> d + 1
Decimal('4.141')

>>> decimal.getcontext().prec = 2
>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.33')

>>> from fractions import Fraction
>>> f = Fraction(2, 3)
>>> f + 1
Fraction(5, 3)
>>> f + Fraction(1, 2)
Fraction(7, 6)

用户定义的类

>>> class Worker:
    	def __init__(self, name, pay):
            self.name = name
            self.pay = pay
         def lastName(self):
            return self.name.split()[-1]
         def giveRaise(self, percent):
            self.pay *= (1.0 + percent)

>>> bob = Worker('Bob Smith', 50000)
>>> sue = Worker('Sue Jones', 60000)
>>> bob.lastName()
'Smith'
>>> sue.lastName()
'Jones'
>>> sue.giveRaise(.10)
>>> sue.pay
66000.0
posted @ 2018-06-08 12:07  freedomwater  阅读(197)  评论(0编辑  收藏  举报
hljs.initLineNumbersOnLoad(); });