lulu10922 / gitblog

People Die, but Long Live GitHub
MIT License
0 stars 0 forks source link

python学习 #4

Open lulu10922 opened 1 year ago

lulu10922 commented 1 year ago

re --- 正则表达式操作

re是python标准库中的模块,本模块提供了与 Perl 语言类似的正则表达式匹配操作。

绝大部分Python的标准转义字符也被正则表达式分析器支持。

例:

import re

str = re.split(':|\r\n', s)

速查

lulu10922 commented 1 year ago
import collections

###namedtuple, access tuple member by name and index is both ok now!
Card_test = collections.namedtuple('Card', ['rank', 'suite'])
class FrenchDeck:
    ###list(string) ==> list
    ranks = [str(n) for n in range(2, 11)] + list("JQKA")
    ###string.split() ==> list
    suits = "spades diamonds clubs hearts".split()

    def __init__(self):
        self._cards = [Card_test(rank, suit) for rank in self.ranks for suit in self.suits]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]

deck = FrenchDeck()
print("len: %d" % len(deck))
print(deck[0])
lulu10922 commented 1 year ago

第2章 序列构成的数组

容器序列 list, tuple, collections,deque这些序列能存放不同类型的数据

扁平序列 str, bytes, bytearray, memoryview, array.array,这类序列只能容纳一种类型

容器序列存放的是他们所包含的任意类型的对象的引用,而扁平序列存放的是值而不是引用。换句话说,扁平序列其实是一段连续的空间

lulu10922 commented 1 year ago

列表推导

tshirts = [(color, size) for color in colors
                                   for size in sizes]

是的,python会忽略代码里[], {}和()中的换行 列表推导作用只有一个:生成列表。如果想生成其他类型的序列,生成器表达式就派上用场了。

生成器表达式

虽然也可以用列表推导来初始化元组,数组或其他序列类型,但生成器表达式是更好的,因为它可以逐个的产出元素,而不是先建立一个完整的列表,再把它传到某个构造函数里。 生成器表达式的语法和列表推导差不多,只是把方括号换成圆括号,且如果它是函数的唯一参数,那么圆括号也可以省掉:

sysmbols = '#$@%hg'
tuple(ord(symbol) for symbol in symbols)
array.array(I, (ord(symbol) for symbol in symbols))
lulu10922 commented 1 year ago

元组拆包(可迭代元素拆包)

可以用*运算符把一个可迭代对象拆开作为函数的参数:

#divmod函数需要两个参数
t = (20, 8)
divmod(*t)

使用*也可以帮助我们把注意力集中在元组的部分元素上:

a, b, *rest = range(5)
#print(a, b, rest): 0, 1, [2, 3, 4]

a, *body, c, d = range(5)
#print(a, body, c, d): 0, [1, 2], 3, 4

具名元组

collections.namedtuple

创建一个具名元组需要两个参数,一个是类名,另一个是类的各个字段的名字,后者可以是由数个字符串组成的可迭代对象,也可以是由空格分隔开的字段名组成的字符串

lulu10922 commented 1 year ago

切片

在python里,像列表、元组和字符串这类序列类型都支持切片操作,但实际上,切片操作比想象的要强大的多。

可以用s[a:b:c]的形式对s在a和b之间以c为间隔取值。

>>> s = 'bicycle' 
>>> s[::3] 
'bye'
>>> s[::-1] 
'elcycib'

对序列使用+和*

>>> l=[1,2,3] 
>>> l*5
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

小陷阱:如果在a*n这个语句中,序列a里的元素是对其他可变对象的引用,就要格外注意了。

>>> weird_board = ['_']*3
>>> weird_board
['_', '_', '_']
>>> weird_board = [['_']*3]*3
>>> weird_board
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
>>> weird_board[0][2] = '0' 
>>> weird_board
[['_', '_', '0'], ['_', '_', '0'], ['_', '_', '0']]

上面产生的列表内部的三个列表是指向的同一个对象的引用,它等同于:

row = ['_'] * 3
for i in range(3):
    board.append(row)

正确的做法是:

>>> [['_']*3 for i in range(3)]
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]

list.sort和内置函数sorted

list.sort()方法会原地排序,sorted则会建立新的列表作为返回值 都有两个可选的关键字: reverse,key

当列表不是首选时

数组

array.array 支持所有跟可变序列有关的操作,.pop、.insert、.extend。数组还提供从文件读取和存入文件的更快的方法,如.frombytes和.tofile 创建数组需要一个类型码,这个类型码用来表示在底层的C语言存放怎样的数据类型。如b表示有符号的字符。 创建1000万个随机浮点数的数组,存到文件里,再从文件读取:

>>> from array import array
>>> from random import random
>>> floats = array('d', (random() for i in range(10**7)))
>>> floats[-1] 
0.22366972376507777
>>> fp=open('float.bin', 'wb') 
>>> floats.tofile(fp) 
>>> fp.close()
>>> floats2 = array('d')
>>> fp = open('float.bin', 'rb') 
>>> floats2.fromfile(fp, 10**7)  
>>> fp.close()
>>> floats2[-1] 
0.22366972376507777