Python3 study notes _A (basic types)


Notes code can be run in Jupyter NoteBook (actually Jupyter-lab experience is great).

Recommended not to look, to be more hands to knock code. Eye over a thousand was better to hand read it again.

Jupiter run code related notes have been uploaded, downloaded from your own resources.

#在download源代码的时候要适当选择较低的版本,因为语言的源码版本越低越能看出作者的意图

python comments

python encoding formats Notes: # - * - coding: utf-8 - * -

Writing linux environment variables Notes:! # / usr / bin / env python3

'''python中的帮助函数:help(func_name)'''
# 例子
help(input)
# 例子结束
Help on method raw_input in module ipykernel.kernelbase:

raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
    Forward raw_input to frontends
    
    Raises
    ------
    StdinNotImplentedError if active frontend doesn't support stdin.

Operators python

#算数运算符
'''python中 / 表示浮点除法  //  向下取整除法'''
# 例子
print(3/4)
print("*"*8)# python符号也可进行算数运算
print(3//4)
# 例子结束

python comparison operators:>, <!,> =, <=, ==, =, <> (not equal to such a representation will be gradually phased out)

python logical operators and, or, not

'''
python赋值运算符:=, +=, -=,*=,/=,**= (算术运算符和=相结合的操作)

python 位运算符:&[按位与,同为1,否则为假],| [按位或,二者中一个即可]
^ [按位异或,相异为1],~[按位取反,1变0,0变1],
<<[左移,乘2],>>[右移,除以2]

进制转换 :转二进制:bin(),八进制:oct(),16进制:hex(),转10进制:int()

'''
#例子
a=3
print(a<<1)
b=4
print(b>>1)
# 例子结束

# python 成员运算符:in,not in
# python身份运算符:is, is not
'''is和 == 的区别:is用于判断两个变量引用是否为同一个(即id是否相同),==用于判断变量值是否相等'''
# 例子
x=y=[1, 2, 3]
z=[1, 2, 3]
print(x is y, id(x),id(y), x==y)
print(x is z, id(x), id(z), x==z)

6
2
True 140646103441800 140646103441800 True
False 140646103441800 140646103444296 True
'''
对于python中a,b = b,a的换值方法的解析
a, b = b, a操作是将a,b的地址互换
关键在于ROT_TWO的地址互换
'''
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
from dis import dis

def demo(a, b):
    print(a,b)
    a, b = b, a
    print('new: ', a,b)


a, b = 2, 3

demo(a,b)

dis(demo)

2 3
new:  3 2
 10           0 LOAD_GLOBAL              0 (print)
              2 LOAD_FAST                0 (a)
              4 LOAD_FAST                1 (b)
              6 CALL_FUNCTION            2
              8 POP_TOP

 11          10 LOAD_FAST                1 (b)
             12 LOAD_FAST                0 (a)
             14 ROT_TWO
             16 STORE_FAST               0 (a)
             18 STORE_FAST               1 (b)

 12          20 LOAD_GLOBAL              0 (print)
             22 LOAD_CONST               1 ('new: ')
             24 LOAD_FAST                0 (a)
             26 LOAD_FAST                1 (b)
             28 CALL_FUNCTION            3
             30 POP_TOP
             32 LOAD_CONST               0 (None)
             34 RETURN_VALUE

Compare: type () and isinstance ()

'''type()和isinstance()区别
type()不认为子类是父类的一种类型,而isinstance()认为是
isinstance()也用来判断是不是可迭代对象'''
#l例子
class A:
    pass
class B(A):
    pass
print("isinstance(, A(),A) is ", isinstance(A(),A))
print("type(A())==A is ",type(A())==A)
print("isinstance(B(),A) is ", isinstance(B(),A))
print("type(B())==A is ",type(B())==A)
isinstance(, A(),A) is  True
type(A())==A is  True
isinstance(B(),A) is  True
type(B())==A is  False

Basic data types

# 变量可使用del语句删除
# 例子
vara=1
print(vara)
del vara
print(vara) # 删除后打印会报错
1



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-2-1f49fa2b38a1> in <module>()
      4 print(vara)
      5 del vara
----> 6 print(vara) # 删除后打印会报错


NameError: name 'vara' is not defined
'''
六个标准数据类型:
Number(数字),String(字符串),List(列表),Tuple(元组),Set(集合),Dictionary(字典)

不可变数据:Number,String,Tuple

可变数据:list,dict,set
'''

Number (Digital)

int, float, bool, complex (plural)

#例子
complex(1,3)
(1+3j)
Mathematical Functions
'''ads(x)[绝对值],ceil(x)[向上取整],

cmp(x,y)[比较xy,x>y=1,x<y=-1,x==y=0,<python3已弃用,使用(x>y)-(x<y)>]

exp(x)[e的x次方],fabs(x)[浮点绝对值],floor(x)[向下取整],

pow(x,y)[x的y次],round(x,y)[对x四舍五入,y表示精确度]
'''
# abs()与fabs()比较
from math import fabs
print(abs(-5))
print(fabs(-5))
# round(x,y)例子
print(round(5.6482133, 5))

5
5.0
5.64821
Random number function
'''
choice(seq)[从序列seq中随机挑一个](在模块random中)
randrange([start,]stop[,step])
random()[随机在(0-1中生成)]
seed([x])[改变随机数生成器种子]
shuffle(lst)[随机排序一个序列]
uniform(x,y)[在(x-y中随机生成一个浮点数)]
'''
# choice()例子
import random
print("choice()例子:", random.choice(range(10)))

# randrange()使用例子
print("randrange()例子:", random.randrange(1,90,1)) # 随机数范围为1-90,步长为1
# seed()不常使用

# shuffle()例子
var_shuffle_ =[1, 2, 3, 4, 5]
random.shuffle(var_shuffle_)
print(var_shuffle_)

# uniform()例子
print("uniform例子:", random.uniform(1, 45))
choice()例子: 0
randrange()例子: 79
[3, 4, 5, 2, 1]
uniform例子: 4.053759455798719
from math import pi
print(pi)
3.141592653589793

String

'''
原始字符串:r/R
'''
#例子
a = r'test\n'
print('test\n')
print(a)

test

test\n
Formatted output
# 格式化输出可以用% 和"str".format()
# "str".format()中在字符串"str"中用{[var]}表示变量,[var]为可选的变量名
# 这里注意:{}中无变量名,切未指示位置的时候,无变量名的参数应在有变量名的参数的位置前面
# 在{}中表示数字时用':'(冒号),表示数字格式化
# format()还可以在"str"的{}中通过指定位置来输出
# 在format中对大括号的转义用{},例子{{}}
'''
%c[字符,或ascii码]
'''
print("这是 %s" %('用%格式化输出例子'))

# format()格式化输出例子
print("这是{name}{}".format('有无变量名混用的例子', name='format'))
print("这是{0}而不用{1}的例子,{1}{0}".format("通过位置输出", "变量名输出"))
from math import pi
print("这是数字格式化例子:输出保留两位小数的pi{:.2f}, 不设置保留位数的pi={ppi}".format(pi,ppi=pi))
print("format对{{}}的转义例子输出".format())
这是 用%格式化输出例子
这是format有无变量名混用的例子
这是通过位置输出而不用变量名输出的例子,变量名输出通过位置输出
这是数字格式化例子:输出保留两位小数的pi3.14, 不设置保留位数的pi=3.141592653589793
format对{}的转义例子输出
String built-in functions
'''
capitalize()[首字母大写],

center(width,fillchar)[在宽度为width的输出空间中居中显示fillchar字符串],

count(str,beg=0,end=len(string))[统计str在string中出现的次数,
若beg或end指定,则返回指定范围的次数],

bytes.decode(encoding="utf-8",errors="strict")[指定解码,
用的是bytes对象的方法]

encode(encoding="utf-8",errors='strict')[指定编码方式]

查找:find,index,rfind,rindex(相同都返回下标,不同,-1,异常)

replace(原,现):替换

split(切割符) :切割

capitalize:单个首字母大写

title:全部首字母大写

endswith(str):判断结尾

startswith(str):判断开头

rjust(int),ljust(int),center(int):在int个字符中右左中对齐

strip():去掉str两边空格,\n

partition(str):以左起第一个str分割为元组

split(str):以str分割

isalpha():是否纯字母

isalnum():是否数字字母组合

isdigit():是否纯数字

str.join(a,b):以str连接a,b

'''

List list

'''
列表切片:list[start:end [:step(默认为1)]]
'''
# 列表生成器
[x for x in range(0,10,2)]
[0, 2, 4, 6, 8]
increase
''' list.
append():追加(整体添加)

insert(位置,内容):添加

extend(list):追加list(合并list)
'''
#例子
A=[12,34,55]
B=['aa','bb']

print('this is A:',A,'\nthis is B:',B)
A.append(666)
print('this is A.append(666)',A)
B.insert(1,'this is 1')
print('this is B.insert:',B)
A.extend(B)
print('A.extend(B)',A)
this is A: [12, 34, 55] 
this is B: ['aa', 'bb']
this is A.append(666) [12, 34, 55, 666]
this is B.insert: ['aa', 'this is 1', 'bb']
A.extend(B) [12, 34, 55, 666, 'aa', 'this is 1', 'bb']
delete
''' list.
pop():默认最后一个

remove(str):删除str内容

clear():清空列表

del list[position]:删除列表中的某个元素
'''
#例子
A=[11,22,33,44]
print(A)
print('*'*8)
print("list.pop()操作")
#A.pop()会返回弹出值
print(A.pop())
print(A)
print('*'*8)
print("del list[position]操作")
del A[1]
print(A)
print('*'*8)
print("list.remove()操作")
A.remove(11)
print(A)
print('*'*8)
print("list.clear()操作")
A.clear()
print(A)
[11, 22, 33, 44]
********
list.pop()操作
44
[11, 22, 33]
********
del list[position]操作
[11, 33]
********
list.remove()操作
[33]
********
list.clear()操作
[]
change
'''
直接用下标进行修改
'''
#例子
A=[11,22,33]
print(A)
print('*'*8)
A[0]="changed"
print(A)
[11, 22, 33]
********
['changed', 22, 33]
check
'''
in:布尔值

list.index:下标,异常
'''
#例子
A=[11,22,33]
print(11 in A)
print(A.index(1234))
True



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-17-f32251f40118> in <module>()
      7 A=[11,22,33]
      8 print(11 in A)
----> 9 print(A.index(1234))


ValueError: 1234 is not in list
Other built-in functions
''' list.
count(obj) 统计obj出现次数

reverse() 反向排列

sort([key=None,reverse=False]) 排序,key表示排序依据,
reverse表示反向,默认False


copy() 复制列表
'''

'''
len(list):list长度
max(list):list中的最大值
min(list):list中的最小值
list(seq):将元组转换为list
'''
A = [1, 2, 3, 4]
B = (22, 33)
print("对A的操作:len(A): {lena}\tmax(A):{maxa}\tmin(A):{mina}\n".format(lena=len(A), maxa=max(A), mina=min(A)))
print("对B的操作:list(B):{listb}".format(listb=list(B)))
对A的操作:len(A): 4	max(A):4	min(A):1

对B的操作:list(B):[22, 33]

Tuple

'''
不可更改的列表,死的
扩展通过新建一个组合元组
tuple(list):将list转换为tuple
'''

dictionary

increase
'''
dict['key']='value'
'''
delete
'''
del dict["key"] 删除键名为"key"的键值对
pop(key,[default]) 删除字典给定键的键值对,返回被删除的值,key必须给出
popitem() 随机删除并返回一对键值对(一般删除的是末尾的键值对)
'''
change
'''
键值对赋值
dict.update(dict2) 把字典dict2中的键值对更新到dict中
'''
dict_a = {'name':'value'}
dict_b = {'name':'18'}
print(dict_a)
dict_a.update(dict_b)
print(dict_a)
{'name': 'value'}
{'name': '18'}
check
'''
dict.get(key)
in

'''
Other built-in functions
'''
len(dict):键值对个数

dict.keys():dict的所有键

dict.values():dict的所有值

dict.
clear() 清空字典
copy() 浅复制
fromkeys() 创建新字典
ietms() 以列表返回可遍历的键值对



'''
#例子
D={'a':'111','b':222}
print(D)
print(D.items())
D.clear()
print(D)
{'a': '111', 'b': 222}
dict_items([('a', '111'), ('b', 222)])
{}

Collection set

'''
集合中没有重复值,(集合会自动去重)

list、tuple可以有重复值,不会自动去重

字典中,当键重复时,会保留最后的那个,其他的去重(不论值是否相同)

强制类型转换得到的变量恢复到原类型用eval()
'''
increase
'''set.
add() 添加元素


'''
delete
'''set.
pop() 随机移除
remove() 移除指定元素,当元素不存在会报错
discard() 删除指定元素, 当元素不存在不会报错
clear() 清空

'''
other
'''set.
copy() 拷贝
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
intersection() 返回交集
isdisjoint() 布尔判断集合间是否包含相同元素
issubset() 子集判断
union() 并集
'''

Conditions control

'''
if exp:
    pass
elif exp1:
    pass
else:
    pass
    
if的各种真假判断

"",None,[],{},数字0,都表示假
'''

cycle

'''
while exp:
    pass

while exp:
    pass
else:
    pass

for var in seq: # 这里seq必须是可迭代数据
    pass
    
break
continue
'''
'''
for循环中删除元素的坑:在循环的过程中删除元素可能出现漏删的情况。
'''
# for循环例子
a = [1,2,3,4,5,6,7]

for i in a:
    print(i, end=',')
    if i == 2 or i == 3:
        a.remove(i)
print("\na = {0}".format(a))

#这时输出分别为1,2,4,5,6,7,和a = [1,3,4,5,6,7]
#从这里的结果可以看出在循环中漏删了3
1,2,4,5,6,7,
a = [1, 3, 4, 5, 6, 7]
'''
这里可以使用“缓存”的方法

用另一个变量临时存储要删除的变量,待循环结束后在删除
'''
# for循环解决例子
a = [1,2,3,4,5,6,7]

b = []

for i in a:
    print(i, end = ",")
    if i == 2 or i == 3:
        b.append(i)

for i in b:
    a.remove(i)
print("\na = {0}".format(a))

#此时得到的a的结果就是完全删除的结果 a = [1,4,5,6,7] 
1,2,3,4,5,6,7,
a = [1, 4, 5, 6, 7]
Published 13 original articles · won praise 0 · Views 29

Guess you like

Origin blog.csdn.net/qq_34764582/article/details/104939857