Python学习笔记


title: Python学习笔记

基础

创建:

test = {
    'a':'1',
    'b':'asdf'
}

遍历

遍历键 值

    for key, value in test.items():
        print(key+':'+value)        

只遍历 键名

    for key in test.keys():
        print(key)

只遍历 值

    for value in test.values():
        print(value)

输出控制

用空格字符结尾

print("and", end =" ")
print("c", end =" ")

Python 核心编程

关于各类括号

“()” :
主要应用在限制多选结构的范围/分组/捕获文本/环视/特殊模式处理
示例:
1、(abc|bcd|cde),表示这一段是abc、bcd、cde三者之一均可,顺序也必须一致
2、(abc)?,表示这一组要么一起出现,要么不出现,出现则按此组内的顺序出现
3、(?:abc)表示找到这样abc这样一组,但不记录,不保存到(变量中,否则可以通过)x取第几个括号所匹配到的项,比如:(aaa)(bbb)(ccc)(?:ddd)(eee),可以用$1获取(aaa)匹配到的内容,而$3则获取到了(ccc)匹配到的内容,而$4则获取的是由(eee)匹配到的内容,因为前一对括号没有保存变量
4、a(?=bbb) 顺序环视 表示a后面必须紧跟3个连续的b
5、(?i:xxxx) 不区分大小写 (?s:.*) 跨行匹配.可以匹配回车符
6、(.+) 表示重复出现(.+)中的内容n次。返回'NoneType',因此不能调用其group()函数
“[]” :
单个匹配,字符集/排除字符集/命名字符集
示例:
1、[0-3],表示找到这一个位置上的字符只能是0到3这四个数字,与(abc|bcd|cde)的作用比较类似,但圆括号可以匹配多个连续的字符,而一对方括号只能匹配单个字符
2、[^0-3],表示找到这一个位置上的字符只能是除了0到3之外的所有字符
3、[:digit:] 0-9 [:alnum:] A-Za-z0-9
“{}” :
"9{i, j}" 表示在字符串中重复出现1到3次

关于re.match()

只能够从起始位置开始匹配,即使匹配规则中使用了$符号

关于元字符(metacharacters)

“ . ” 表示匹配非换行符的任何字符
“ ^ ” 表示字符串的起始位置
“ $ ” 表示字符串的结束位置

“[^A-Z]” 表示匹配除了A-Z的所有字符

通配符 关于转义字符

import re
str1 = "st"
str2 = r"st"

上述区别:
r 表示转义,也就是说
str1 中  表示 backspace
str2 中  表示 对有边界字符进行匹配的通配符

关于匹配处理

re.I 忽略大小写
re.M 输出所有行的尾字母

关于通配符方法的特殊返回值

findall()方法返回一个list对象
Exp:

import re
str1 = "car"
str2 = "bcaray is in the car of Carry's carbox"
m = re.findall(str1, str2)
print(type(m))
if m is not None:
    for i in m:
        print(i, end = ' ')

输出:

<class 'list'>
car car car 

finditer()方法返回一个可供迭代的对象)
Exp:

import re
str = "This and that"
m = re.finditer(r"(thw+) and (thw+)", str, re.I)
print(type(m))
if m is not None:
    for i in m:
        print(i.groups())

输出:

<class 'callable_iterator'>
('This', 'that')

sub()返回字符串
Exp

subn()返回元组

关于非捕获组

(?:...)

上述代码被称作非捕获组,作用为
(?:X) X,作为非捕获组
与捕获组 ( ) 的意思一样也是将其作为一组进行处理,与捕获组的区别在于不捕获匹配的文本,
仅仅作为分组。
比如:要匹配 123123 这个,就可以写为 (123)/1 使用反向引用,这时只能用捕获组,在匹配
123 后会保留在内存中,便于反向引用,而 (?:123) 在匹配完后则不会保留,区别仅在于此。
引用自CSDN
https://blog.csdn.net/zfq642773391/article/details/5555602

python 基础

关于Python 几种 itertools 的使用方法

count

for i in count(5):
    print(i)
    if i >= 12:
        break

output:
5
6
7
8
9
10
11
12

cycle

from itertools import cycle

for item in cycle("asdf"):
    print(item)
    if c >= 5:
        break

output:
a
s
d
f
a
s
d
f
a
s
d
...
按照字符串中字母排列顺序无限循环地输出字符串中的每个元素

repeat

from itertools import repeat

for item in repeat("asdf", 3):
    print(item)
    

output:
asdf
asdf
asdf
repeat("字符串", cycle_times)

accumulate

from itertools import repeat, accumulate

print(list(accumulate(range(5))))

accumulate(range(n)) 返回0~n项等差数列(步长为1)的和

takewhile

from itertools import takewhile

nums = [1,2,3,4,5,6,7,8]
print(list(takewhile(lambda x : x <= 3, nums)))

output:
[1, 2, 3]
takewhile 计算到条件不符合的那个数就会停止计算,返回所得到的数值

product

from itertools import product
letters = ("A", "B")
print(list(product(range(3), letters)))

output:
[(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
product 个人理解类似于组合
product(A, B),它是将 A 中的所有元素当作x,与 B 中所有元素(当作y)进行组合
例如
A : ["x1", "x2", "x3"]
B : ["y1", "y2"]
list(product(A, B)) : [('x1', 'y1'), ('x1', 'y2'), ('x2', 'y1'), ('x2', 'y2'), ('x3', 'y1'), ('x3', 'y2')]

permutations

from itertools import permutations
a = ["x1", "x2", "x3"]
print(list(permutations(a))

output:
[('x1', 'x2', 'x3'), ('x1', 'x3', 'x2'), ('x2', 'x1', 'x3'), ('x2', 'x3', 'x1'), ('x3', 'x1', 'x2'), ('x3', 'x2', 'x1')]
permutations 其功能如同其译名——排列
就是将某一变量中的所有数据进行排列

Magic Methonds

__sub__ for -
__mul__ for *
__truediv__ for /
__floordiv__ for //
__mod__ for %
__pow__ for **
__and__ for &
__xor__ for ^
__or__ for |
__lt__ for <
__le__ for <=
__eq__ for ==
__ne__ for !=
__gt__ for >
__ge__ for >=
__len__ for len()
__getitem__ for 相当于重载“[]”运算符
__setitem__ for 重载为已设定下标的数据赋值的函数
__delitem__ for 重载删除函数
__iter__ for iteration over objects (e.g., in for loops)
            (重载迭代器)
__contains__ for in

在python中,在类中重写上述方法能够达到重写运算符的作用
下面是重写方法__and__的例子

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

first = Vector2D(2, 4)
second = Vector2D(4, 6)
result = first + second
print("({0}, {1})".format(result.x, result.y))

上述代码中的other表示另外一个同类对象,如果非同类对象则会报错
如果你需要将该类对象加上一个非该类的对象,则在该类中重写方法__radd__,它意为右加。例如 B + A 中,A 没有重写__add__方法,则在 B 中重写__radd__方法,用

B().__radd__(A())

用这种方式,将两者加和

两种类私有属性

class Test:
    _pam = 12

t = Test()
print(_pam)    

output:
12
上面这种带有一个下划线的变量被称作弱私有变量,它能够直接在外部通过对象调用。

class Test:
    __pam = 24
    def print_pam(self):
        print(self.__pam)
t = Test()
t.print_pam()
print(t._Test__pam)
print(t.__pam)

output:
24
24
AttributeError: 'Test' object has no attribute '__pam'
上面这种带有两个下划线的被称作强私有变量,他不能使用对象直接在外部被调用,而是只能通过类中的方法,或者通过变量名._类名__强私有成员变量名这两种方式调用。

arg的作用

arg使得传入函数的参数数量固定,类型不固定,可以是多种数据类型

def check(arg):
    print(type(arg))

check(6)

输出:

<class 'int'>

*args的作用

*args使得传入函数的参数长度可变,如下例代码所示

def _function(*args):
    print(*args)

_function(1,2,3,4,5,6)
_function(2,3,4,2)

output:
1 2 3 4 5 6
2 3 4 2
其本质是元组

**keyword的作用

*keyword需要传入键值对这样的数据,如下例代码所示

def _function(**keywordss):
    print(keywordss)

_function(a="2", b="4")

output:
{'a': '2', 'b': '4'}
其本质类型是字典

else 的特殊用法

当 else 跟在 while 或 for 等循环之后时,当循环正常退出的时候,才会执行else下的语句,如下例代码

for i in range(10):
    if i == 5:
        break
else:
    print("Normal Exit1")

for i in range(10):
    if i == 99:
        break
else:
    print("Normal Exit2")

output:
Normal Exit2

当 else 跟在 try/except 块之后时,当 try/except 块正常执行完之后,才能进入 else 中,如下例代码

try:
    print(1/2)
except ZeroDivisionError:
    print("Wrong1")
else:
    print("Correct1")

try:
    print(1/0)
except ZeroDivisionError:
    print("Wrong2")
else:
    print("Correct2")

使用 wraps 还原被装饰器修饰后函数的__name__属性

在使用装饰器修饰函数后,由于装饰器的写法中需要返回再装饰器内定义的函数,因此函数的__name__属性会相应改变,例子如下

def decorator_t(func):
    def wrapper(*args, **kwargs):
        print("wrappered")
        func()
    return wrapper

@decorator_t
def test():
    print("testing")

print("-" * 10)
print(test.__name__)
print("-" * 10)

这个时候控制台会输出:

----------
wrapper
----------

有时候这个会对程序的调试与修改造成一定的影响,因此我们需要函数的原有名称
这时候可以使用 wrag 装饰器,还原函数名称
例子如下

from functools import wraps
def decorator_t(func):
    @wraps(fucn)
    def wrapper(*args, **kwargs):
        print("wrappered")
        func()
    return wrapper

@decorator_t
def test():
    print("testing")

print("-" * 10)
print(test.__name__)
print("-" * 10)

再次运行程序,控制台输出如下

----------
test
----------
原文地址:https://www.cnblogs.com/Breathmint/p/10262526.html