Python的学习记录

在这里插入图片描述

Python

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

基础语法

学习于《Python编程:从入门到实践》

命名

  • 数字,字母,下划线构成,数字不能打头,不含空格
  • 区分大小写
  • 不能于关键字重名

数据结构

数字

不可分割的原子类型,包括整数和浮点数

a = 1 #普通赋值
a += 1 #增量赋值
a = b =1 #多重赋值
(x,y) = (1,2) #多元赋值

复数:real + imag j,虚数部分必须用j或J结尾

a_complex = 1+2j
a_complex  #(1+2j)
complex(1,2) #(1+2j)
a_complex.conjugate() #共轭复数 (1-2j)

常用方法

abs(-1)  #绝对值 1
divmod(10,3) #除留余数  (3,1)
pow(2,3) #幂次运算  8
round(5.6) #四舍五入  6
int()
float()
bool()
字符串

由Unicode码位构成的不可变序列

str1 = 'apple'  #单引号和双引号不区分
str2 = "apple"\ #换行需要 \,不收录行前的空格 'apple2'
     "2"
str3 = ''' apple 
     apple'''#三引号任意换行,收录空格  'apple\n     apple'
str()

转义字符:\n(换行符)、\t(Tab制表符)、\'(单引号)、\"(双引号)、 \\ (反斜线)

chr(65)  #整数对应的Unicode字符  A
ord("A)  #相反  65

常用方法

a = "1-2-3-4-5"
b = a.split('-')  #分割 ['1', '2', '3', '4', '5']
'*'.join(b)  #合并  '1*2*3*4*5'
a.strip('\n')  #去除两端指定字符
a.rstrip() #去除右端空格
a.lstrip()
a.find('1') #第一次出现的位置 0  未找到返回-1
a.rfind('1') #最后一次出现的位置
a.count("1") #子串出现的次数
a.replace("1","2",1) #替换指定字符串,替换一次。 #'2-2-3-4-5'
  1. 关系操作符:in ,not in
  2. 连接操作: +
  3. 重复操作符:* ,负数按0处理
  4. 切片操作符:a[];a[:],a[::]
str1 = '1234567'
a[0]   #'1'
a[0:2]  #'12'
a[::-1]  #逆置 '7654321'
a[-1:-3:-1] #负数索引从-1开始  '76',步长不同向则为空
列表

列表由一系列特定顺序排列的元素组成。

a_list = [1,"2",(1,),{22},[1,2]]
list((1,2)) # 创建 [1,2]
a_list[0] # 1  切片操作,同字符串一致
a_list[:2] #[1,"2"]
a_list[::-1]

常用方法

a_list[0] = 2 #修改  [2,"2",(1,),{22},[1,2]]
a_list[:2] = 1,2 #修改
a_list.append(2222)  #增加 [1, '2', (1,), {22}, [1, 2], 2222]
a_list.insert(1,333) #插入指定位置 [1, 333, '2', (1,), {22}, [1, 2], 2222]
a_list.pop(0)  #弹出指定位置值 1
a_list.remove(2) #删除指定的值  ValueError
del a_list[0] #删除指定位置元素,自动补齐
a_list.count("2") #统计值个数
a_list.sort(reverse=True) #永久排序,元素为同一类型时可以,a_list改变
b_list = sorted(a_list) #临时排序,a_list不变
a_list.extend(b_list)#合并,等价于a +=b
a_list.reverse() #逆置
len(a_list) #返回长度
元组

不可变的列表

t = (1,) #单元素逗号结尾
t = (1,2)
t[0]  #取值 1
tuple([1,2]) #创建 (1,2)
a,b = (1,2) #解包 a=1,b=2
字典

python中唯一的映射类型,有键值对构成,键可以被哈希,不能重复,不可变,包括:布尔型,整型,浮点型,元组等。

a = {}  #空字典,而不是空列表
a_dict = {1:3,2:4}
dict([[1,2]]) #创建,参数必须是双值子序列
a_dict[1]   #访问 3
a_dict[3] = 5  #添加
a_dict[1] = 9 #修改 {1:9,2:4,3:5}
del a_dict[1] #删除键值对

常用方法

a_dict.keys()    #键列表  dict_keys([1, 2, 3])
a_dict.values()  #值列表  dict_values([9, 4, 5])
a_dict.items()  #返回键值对元组列表,dict_items([(1, 9), (2, 4), (3, 5)])
a_dict.update(b_dict) #合并 ,b合并到a上
a_dict.pop(1) #弹出指定键
a_dict.clear() #清空 {}
集合

分为可变集合和不可变集合,不可变集合相当于字典中键的集合,元素唯一。

a_set = {1,2}
a_set = set((1,2,3,3)) #{1, 2, 3}

常用方法

a_set.add(4)     #添加  {1, 2, 3, 4}
a_set.remove(4)  #删除 {1, 2, 3}
a_set.update(b)  #更新

子集/超集判定: <、<=、>、>=

a = {1,2,3,4}
b = {2,3,4,5}

a|b  #并集   {1, 2, 3, 4, 5}
a&b  #交集   {2, 3, 4}
a-b  #差集   {1}
a^b  #对称差集 {1, 5} = 并集-交集

可用于所有集合的方法

s.issubset(t)            # 如果s是t的子集,返回True
s.issuperset(t)          # 如果s是t的超集,返回True
s.union(t)               # 返回一个新集合(s和t的并集)
s.intersection(t)        # 返回一个新集合(s和t的交集)
s.difference(t)          # 返回一个新集合(s - t)
s.symmetric_difference(t)# 返回一个新集合(s ^ t)
s.copy()                 # 返回一个新集合,它是s的浅复制

仅用于可变集合的方法

s.update(t)              # 用t中的元素更新s
s.intersection_update(t) # s中现在是s和t的交集
s.difference_update(t)   # s中现在是(s - t)
s.symmetric_difference_update(t)
                         # s中现在是s和t异或的结果
s.add(obj)               # 在s中添加对象obj
s.remove(obj)            # 从s中删除对象obj,如果不存在则引发KeyError异常
s.discard(obj)           # 如果obj是s的元素,就从s中删除
s.pop()                  # 删除s中任意一个对象,并返回
s.clear()                # 删除集合s中的所有元素
循环结构

for循环

for i in range(5):
    print(i,end=" ")  #0 1 2 3 4 

print(1 if 2<3 else 2)#三元操作符

while循环

i =0
while(i<5):
    print(i,end=' ')
    i+=1  #0 1 2 3 4 

break:结束循环
continue:跳过当前循环
pass:占位,无实际意义

for i in range(10):
    if( i==1):
        continue
    elif(i==2):
        pass
    elif(i==6):
        break
    
    print(i,end=" ") #0 2 3 4 5 
输入输出

input()获取输入,返回字符串

message = input("请输入内容空格相隔:")
请输入内容空格相隔:1 2 3 4
a,b,c,d = message.split(" ")
a # "1"

print()输出

%s 字符串
%d 十进制数
%x 十六进制数
%o 八进制数
%f 浮点类型数
%e 以科学计数法表示的浮点数
%g 十进制或科学计数法表示的浮点数
%% 文本值%本身

n = 42
f = 7.03
s = 'string cheese'

# 以默认宽度格式化
'%d %f %s' % (n, f, s)  # '42 7.030000 string cheese'

# 最小域宽10个字符,右对齐,左侧不够空格填充
'%10d %10f %10s' % (n, f, s)  # '        42   7.030000 string cheese'

# 将上例 ⬅️对齐
'%-10d %-10f %-10s' % (n, f, s)  # '42         7.030000   string cheese'

# 将上例 ➡️对齐,最大字符宽度为4
'%10.4d %10.4f %10.4s' % (n, f, s)  # '      0042     7.0300       stri'

# 去掉最小域宽为10的限制
'%.4d %.4f %.4s' % (n, f, s)  # '0042 7.0300 stri'

# 将域宽、字符宽度等设定为参数
'%*.*d %*.*f %*.*s' % (10, 4, n, 10, 4, f, 10, 4, s)
# '      0042     7.0300       stri'
'{} {} {}'.format(n, f, s)  # '42 7.03 string cheese'

# 指定插入的顺序
'{2} {0} {1}'.format(f, s, n)  # '42 7.03 string cheese'

# 参数为字典或命名变量,格式串中标识符可以引用这些名称
'{n} {f} {s}'.format(n=42, f=7.03, s='string cheese')  # '42 7.03 string cheese'

d = dict(n=42, f=7.03, s='string cheese')  # {'f': 7.03, 'n': 42, 's': 'string cheese'}
# {0} 代表整个字典,{1}代表字典后面的字符串'other'
'{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other')  # '42 7.03 string cheese other'
'{0:d} {1:f} {2:s}'.format(n, f, s)  # '42 7.030000 string cheese'

'{n:d} {f:f} {s:s}'.format(n=42, f=7.03, s='string cheese')  # '42 7.030000 string cheese'
函数

定义:

def doing(*args,**kwargs):
	return 0  #可省
doing()

参数的传递

  • 传递可变对象的引用(字典,列表,集合等),在函数体内不创建新的对象,而是直接修改所传递的对象。(传递列表的副本,不影响原件,a[:])
  • 传递不可变对象的引用(数字,字符串,元组),由于对象不可变,会创建新的对象。

参数类型

  • 位置参数:def doing(a,b,c),参数顺序有要求
  • 关键字参数:def doing(a =1,b=2),传参是指定键名
  • 可变位置参数:def doing(*args),使用来收集任意数量的位置参数,为元组格式。
def print_more(arg1, arg2, *rest_args):
    print(arg1,end=" ")
    print(arg2, end=" ")
    print(rest_args)

print_more(3, 2, 1) #3 2 (1,)
  • 可变关键字参数:def doing(**kwargs),为字典格式。
def print_kwargs(**kwargs):
    print(kwargs)

print_kwargs(arg1=1, arg2=2, arg3='a')
lisr = {'qq':'112'}
print_kwargs(**lisr)
结果:
{'arg1': 1, 'arg2': 2, 'arg3': 'a'}
{'qq': '112'}

匿名函数

a = lambda x:x**2
a(3) #9

class用来实例化对象

class Person():
    pass
p = Person()

方法类型

  • 实例方法(instance method):第一个参数为self
  • 类方法 (class method):第一个参数为类本身,通常写作cls
  • 静态方法 (static method):参数无特殊规定
  • 魔法方法:以双下划线开头和结尾的方法,可以为符号赋予特殊作用。

类方法和静态方法类本身和类的实例化对象都可以调用,实例方法只能实例化对象调用。

class A():
    count = 0
    def __init__(self):
        A.count += 1
    
    @classmethod
    def kid(cls):
        print('A has', cls.count, 'little objects')
    
    @staticmethod
    def static_method():
        print('Static method called!')

魔术方法

class Word():
    def __init__(self, text):
        self.text = text
    
    def __eq__(self, word2):
        return self.text.lower() == word2.text.lower()

first = Word('ha')
second = Word('HA')
first == second #True

  • 用于比较的魔术方法
__lt__(self, other)    self < other
__le__(self, other)    self <= other
__eq__(self, other)    self == other
__ne__(self, other)    self != other
__gt__(self, other)    self > other
__ge__(self, other)    self >= other
  • 普通算数操作符
__add__(self, other)      加法 +
__sub__(self, other)      减法 -
__mul__(self, other)      乘法 *
__floordiv__(self, other) 整数除法 //
__truediv__(self, other)  真除法 /
__mod__(self, other)      取模算法 %
__divmod___(self, other)  内置divmod()函数
__pow__(self, other)      指数运算 **
__lshift__(self, other)   左移 <<
__rshift__(self, other)   右移 >>
__and__(self, other)      按位与 &
__or__(self, other)       按位或 |
__xor__(self, other)      按位异或 ^
  • 其他的魔术方法
__str__(self) 等价于str(self),定义如何打印对象信息,print()str()以及字符串格式化相关方法都会用到__str__()。
__repr__(self) 等价于repr(self),交互式解释器适用此方法输出变量。
__len__(self) 等价于len(self)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值