python基础(二)—-数据类型

进制转变

就算Computer只认知二进制,可是为了投其所好大家的习于旧贯,python的数字暗中同意依旧十进制。还提供了一部分艺术来提携大家做转变,举例是进制转换为二进制使用[`bin]
方法,在改动结果眼下还大概会增多0b意味着是三个二进制的数。

>>> num = 132
>>> bin(num)
'0b10000100'

既然十进制能够转换为二进制,那么实际上使用一样的规律也可以转变为别的进制,python也为大家提供了十进制转变到八进制和十六进制的法子,分别是oct和hex。八进制前边以0o表示
,十六进制以0表示

>>> num = 129
>>> oct(num)
'0o201'
>>> hex(num)
'0x81'

列表的大规模操作

此间用了分化的列表,请留神查看!

append() 追加一个元素在列表的末梢

list = [‘xiaoyafei’]
list.append(‘lipeng’)
list
[‘xiaoyafei’, ‘lipeng’]

切片

#切下表为2到下标为4的元素,顾头不顾尾
>>> list
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[2:5]
['zhangsan', 'lisi', 'wanger']

#切下表为2到最后的元素,顾头也顾尾
>>> list
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[2:]
['zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']

#切从第一个到最后一个
>>> list
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[:]
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']

#切最后两个,顾头也顾尾
>>> list
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[-2:]
['zhaoliu', 'likun']

# 步长语句,只切下表为奇数
>>> list
['xiaoyafei', 'lipeng', 'zhangsan', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[::2]
['xiaoyafei', 'zhangsan', 'wanger', 'zhaoliu']

count() 查看存在多少等同的成分

list1
[2, 2, 3, 4, 1, 2]
list1.count(2)
3
list2 = [‘lipeng’,’likun’,’lipeng’,’weiwenwu’,’lihang’,’lisiru’,’lipeng’]
list2.count(‘lipeng’)
3

index() 获取成分的下标

list
[‘xiaoyafei’, ‘lipeng’, ‘zhangsan’, ‘lisi’, ‘wanger’, ‘mazi’, ‘zhaoliu’, ‘likun’]
list. #tab键
list.add( list.dir( list.getattribute( list.imul( list.lt( list.reduce_ex( list.setitem( list.clear( list.insert(
list.class( list.doc list.getitem( list.init( list.mul( list.repr( list.sizeof( list.copy( list.pop(
list.contains( list.eq( list.gt( list.iter( list.ne( list.reversed( list.str( list.count( list.remove(
list.delattr( list.format( list.hash list.le( list.new( list.rmul( list.subclasshook( list.extend( list.reverse(
list.delitem( list.ge( list.iadd( list.len( list.reduce( list.setattr( list.append( list.index( list.sort(
list.index(‘lipeng’)
1

赢得钦点下标的值

list
[‘xiaoyafei’, ‘lipeng’, ‘zhangsan’, ‘lisi’, ‘wanger’, ‘mazi’, ‘zhaoliu’, ‘likun’]
list[2]
‘zhangsan’

insert() 插入一个成分

list
[‘xiaoyafei’, ‘lipeng’, ‘zhangsan’, ‘lisi’, ‘wanger’, ‘mazi’, ‘zhaoliu’, ‘likun’]

# 在下表为3的元素前插入一个元素

list.insert(3,’xixihaha’)
list
[‘xiaoyafei’, ‘lipeng’, ‘zhangsan’, ‘xixihaha’, ‘lisi’, ‘wanger’, ‘mazi’, ‘zhaoliu’, ‘likun’]

列表的改换

list2
[‘lipeng’, ‘likun’, ‘lipeng’, ‘weiwenwu’, ‘lihang’, ‘lisiru’, ‘lipeng’]
list2[2] = ‘xixihaha’
list2
[‘lipeng’, ‘likun’, ‘xixihaha’, ‘weiwenwu’, ‘lihang’, ‘lisiru’, ‘lipeng’]

# 想要连续修改或者批量修改,可以使用切片,因为会把字符串拆掉,不够的话会自动创建
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi', 'wanger', 'mazi', 'zhaoliu', 'likun']
>>> list[5:] = 'xixihaha'
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi', 'x', 'i', 'x', 'i', 'h', 'a', 'h', 'a']

pop() 删除列表的末梢二个要素

list2
[‘lipeng’, ‘likun’, ‘xixihaha’, ‘weiwenwu’, ‘lihang’, ‘lisiru’]
list2.pop()
‘lisiru’ #会把删除的事物打字与印刷出来
list2
[‘lipeng’, ‘likun’, ‘xixihaha’, ‘weiwenwu’, ‘lihang’]

remove() 删除钦命元素

list2
[‘lipeng’, ‘likun’, ‘xixihaha’, ‘weiwenwu’, ‘lihang’]
list2.remove(‘likun’) #删除成分不会打字与印刷list2
[‘lipeng’, ‘xixihaha’, ‘weiwenwu’, ‘lihang’]

# 也可以使用del
>>> list2
['lipeng', 'xixihaha', 'weiwenwu', 'lihang']
>>> del list2[1]
>>> list2
['lipeng', 'weiwenwu', 'lihang']

# 批量删除
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi', 'x', 'i', 'x', 'i', 'h', 'a', 'h', 'a']
>>> del list[5:]
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi']

    pop()和remove()和del的区别:
        在于pop()函数删完元素之后,会将删除的元素打印出来,而remove()函数以及del不会打印

列表的巡回

list
[‘xiaoyafei’, ‘lipeng’, ‘xixihaha’, ‘xixihaha’, ‘lisi’]
for i in list:
… print(i)

xiaoyafei
lipeng
xixihaha
xixihaha
lisi

    for和while的区别:
        while是可以支持死循环的,例如while True,而for循环是有边界的

sort() 依据ASCII码标表顺序排序

# 有重复的元素,但是在排序时就去重了
>>> list3 = ['a','b','c','d','e','A','D','c','f','g']
>>> list3.sort()        不会立马就打印出来
>>> list3
['A', 'D', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'g']

reverse() 把方方面面列表倒过来

list3
[‘A’, ‘D’, ‘a’, ‘b’, ‘c’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
list3.reverse()
list3
[‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘c’, ‘b’, ‘a’, ‘D’, ‘A’]

把三个列表进行相加

list
[‘xiaoyafei’, ‘lipeng’, ‘xixihaha’, ‘xixihaha’, ‘lisi’]
list3
[‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘c’, ‘b’, ‘a’, ‘D’, ‘A’]
list+list3
[‘xiaoyafei’, ‘lipeng’, ‘xixihaha’, ‘xixihaha’, ‘lisi’, ‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘c’, ‘b’, ‘a’, ‘D’, ‘A’]

# 或者也可以使用extend()函数
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi']
>>> list3
['g', 'f', 'e', 'd', 'c', 'c', 'b', 'a', 'D', 'A']
>>> list.extend(list3)      #同样不会立马打印出来
>>> list
['xiaoyafei', 'lipeng', 'xixihaha', 'xixihaha', 'lisi', 'g', 'f', 'e', 'd', 'c', 'c', 'b', 'a', 'D', 'A']

clear() 清空驶列车表

list3
[‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘c’, ‘b’, ‘a’, ‘D’, ‘A’]
list3.clear()
list3
[]

元组的特色

  • 可寄存三个值
  • 不可变,元组本人不可变,不过假若元组还贮存别的可变类型的数据,则是可变的
  • 奉公守法从左到右的一一定义元组成分,下表从0最早逐项访问,有序

布尔型

bool型独有五个值:True和False

据此将bool值归类为数字,是因为大家也习贯用1代表True,0表示False

字典的概念

字典是Python语言中并世无两的投射类型。

>>> info = {
...     'stu1':'zhangsan',
...     'stu2':'lisi',
...     'stu3':'wangwu'
... }

# 也可以使用另一种方法
>>> person = dict({'name':'zhangsan'})

字典的大范围操作

增加

info
{‘stu1’: ‘zhangsan’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’}
info[‘stu4’] = ‘xixihaha’
info
{‘stu1’: ‘zhangsan’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}

修改

info
{‘stu1’: ‘zhangsan’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}
info[‘stu1’] = ‘student1’ #修改的是value
info
{‘stu1’: ‘student1’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}

聚拢去重

# 集合会自动去重
>>> s = {1,1,2,2,3,3,4,4}
>>> s
{1, 2, 3, 4}

将列表调换到集合

list = [1,2,3,4,5,6,7]
s = set(list)
s
{1, 2, 3, 4, 5, 6, 7}

in 查找表示准语法

info
{‘stu1’: ‘student1’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}
‘stu1’ in info
True

获得value值,存在则赶回,不设有不回来任何音信

info
{‘stu1’: ‘student1’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}
info.get(‘stu1’)
‘student1’

# 存在则返回,不存在则报错
>>> info['stu1']
'student1'

pop() 删除

info
{‘stu1’: ‘student1’, ‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}
info.pop(‘stu1’) #会重临删除的音讯 ‘student1’
info
{‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’}

popitem() 随机删除,假若数据量丰裕大那么就是冬季的

info
{‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu1’: ‘zhangsan’, ‘stu5’: ‘lihaha’}
info.popitem()
(‘stu5’, ‘lihaha’)
info.popitem()
(‘stu1’, ‘zhangsan’)

丢弃discard

s
{1, 2, 3, 4, 5, 6, 7}
s.discard(6)
s.discard(10) #固然未有也不会报错

del 删除

person
{‘name’: ‘zhangsan’}
del person
person
Traceback (most recent call last):
File ““, line 1, in
NameError: name ‘person’ is not defined

清空clear()

s
{1, 2, 3, 4, 5, 7}
s.clear()
s
set()

打字与印刷全部key

info
{‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu5’: ‘lihaha’, ‘stu6’: ‘zhangsan’}
info.keys()
dict_keys([‘stu2’, ‘stu3’, ‘stu4’, ‘stu5’, ‘stu6’])

打字与印刷全部value

info.values()
dict_values([‘lisi’, ‘wangwu’, ‘xixihaha’, ‘lihaha’, ‘zhangsan’])

打字与印刷key和value产生元组,把字典转成列表

info
{‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu5’: ‘lihaha’, ‘stu6’: ‘zhangsan’}
info.items()
dict_items([(‘stu2’, ‘lisi’), (‘stu3’, ‘wangwu’), (‘stu4’, ‘xixihaha’), (‘stu5’, ‘lihaha’), (‘stu6’, ‘zhangsan’)])

update 把五个字典合併成一个字典,key有重复则覆盖,未有则新建

info
{‘stu2’: ‘lisi’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu5’: ‘lihaha’, ‘stu6’: ‘zhangsan’}
info2
{‘stu2’: ‘北京’, ‘stu8’: ‘上海’, ‘stu9’: ‘广州’}
info.update(info2)
info
{‘stu2’: ‘北京’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu5’: ‘lihaha’, ‘stu6’: ‘zhangsan’, ‘stu8’: ‘上海’, ‘stu9’: ‘广州’}

setdefault创造,存在则不操作,一纸空文则开创

info2
{‘stu2’: ‘北京’, ‘stu8’: ‘上海’, ‘stu9’: ‘广州’}
info2.setdefault(2,’new2′)
‘new2’
info2
{‘stu2’: ‘北京’, ‘stu8’: ‘上海’, ‘stu9’: ‘广州’, 2: ‘new2’}

fromkeys 不会增多到原来字典个中,而是直接弹出

info.fromkeys([‘a’,’b’,’c’,’d’],[‘xiaoyafei’])
{‘a’: [‘xiaoyafei’], ‘b’: [‘xiaoyafei’], ‘c’: [‘xiaoyafei’], ‘d’: [‘xiaoyafei’]}

字典的大循环

info
{‘stu2’: ‘北京’, ‘stu3’: ‘wangwu’, ‘stu4’: ‘xixihaha’, ‘stu5’: ‘lihaha’, ‘stu6’: ‘zhangsan’, ‘stu8’: ‘上海’, ‘stu9’: ‘广州’}
for i in info:
… print(i,info[i])

stu2 北京
stu3 wangwu
stu4 xixihaha
stu5 lihaha
stu6 zhangsan
stu8 上海
stu9 广州

# 还有一种方法,但是很低效,因为要把字典转换成列表
>>> for k,v in info.items():
...     print(k,v)
...
stu2 北京
stu3 wangwu
stu4 xixihaha
stu5 lihaha
stu6 zhangsan
stu8 上海
stu9 广州

元组的创办

    ages = (11,22,33,44,55)
    或
    ages = tuple(11,22,33,44,55)

列表的定义和创设

定义:[
]内以逗号分隔,依照索引,寄放各类数据类型,每二个职位代表二个要素

Unicode

于是,Unicode应时而生,Unicode把具有语言都统一到一套编码里,那样就不会再有乱码难点了。

Unicode规范也在一再前进,但最常用的是用五个字节表示一个字符(倘若要用到万分偏僻的字符,就供给4个字节)。当代操作系统和大多数编制程序语言都间接帮忙Unicode。
近些日子,捋一捋ASCII编码和Unicode编码的区分:

ASCII编码是1个字节,而Unicode编码常常是2个字节。

字母A用ASCII编码是十进制的65,二进制的01000001;

字符0用ASCII编码是十进制的48,二进制的001一千0;

汉字“中”已经高于了ASCII编码的限制,用Unicode编码是十进制的二零零四3,二进制的0100111000101101。

您能够揣度,若是把ASCII编码的A用Unicode编码,只需求在前头补0就足以,因而,A的Unicode编码是00000000
0一千001。

新的主题素材又出现了,假如都改成Unicode编码的话,乱码问题就能够磨灭,那么随之而来的便是:倘让你写的文件基本上都以英语的话,用Unicode编码要比ASCII编码要求多一倍的上空,在蕴藏和传导上就不行不划算了。

基本数据类型-列表

主导数据类型-字符串

可变、不可变数据类型和hash

    可变类型                不可变类型
    列表                      数字
                             字符串
                             元组

大家看下什么是可变什么是不可变:

列表

list = [1,2,3,4]
id(list)
1602240328712
list.append(5)
list
[1, 2, 3, 4, 5]
id(list)
1602240328712

数字

a = 1
id(a)
1664904208
a += 1
a
2
id(a)
1664904240

字符串

# 示范 1
>>> str = 'hello'
>>> str[1] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
# 示范2
>>> str = 'hello'
>>> id(str)
1602241176272
>>> str += ' world'
>>> str
'hello world'
>>> id(str)
1602241242992

元组

tup = (1,2,3,4)
tup[1] = 3
Traceback (most recent call last):
File ““, line 1, in
TypeError: ‘tuple’ object does not support item assignment

故而:可变不可变重要的分别在于内部存款和储蓄器空间地址是不是产生转移

元组的概念

与列表相似,只然则[]换来了(),大家一般称元组为制度列表

UTF-8

进而,本着节约的神气,又并发了把Unicode编码转化为“可变长编码”的UTF-8编码。UTF-8编码把一个Unicode字符根据不一样的数字大笔者码成1-6个字节,常用的克罗地亚(Croatia)语字母被编码成1个字节,汉字平日是3个字节,唯有很生分的字符才会被编码成4-6个字节。借使您要传输的文件包蕴大批量菲律宾语字符,用UTF-8编码就会节约空间:

    字符  ASCII           Unicode                 UTF-8
    A          01000001     00000000 01000001              01000001
    中              x        01001110 00101101       11100100 10111000 10101101

从上图来看,UTF-8编码有一个优异的实惠,正是ASCII编码实际上能够看作为UTF-8的一部分,所以,一大波只援救ASCII编码的野史遗留软件能够在UTF-8编码下继续工作。

搞领悟了ASCII和、UnicodeUTF-8的区涉及,能够总计一下Computer体系通用的字符编码专门的学业章程:
在微型Computer内部存款和储蓄器中,统一行使Unicode编码,当须要保留到硬盘大概是急需传输的时候,就改变为UTF-8编码;

用记事本编辑的时候,从文件读取的UTF-8字符被转换来Unicode字符到内部存款和储蓄器里,编辑达成后,保存的时候再把Unicode转换成UTF-8封存到文件;

  • windows默认是GBK
  • MacOS\Linux默认为UTF-8

  • Python2编码为ASCII

  • Python3编码为UTF-8

列表的表征

特征:

  • 可贮存几个值
  • 依据从左到右的逐个定义列表成分,下标从0开头所有人家访问,有序
    list    =       ['张三','李四','校长']
    索引                0      1      2
  • 能够修改内定索引的值,可变

Python基础第二章

  • 二进制
  • 字符编码
  • 宗旨数据类型-数字
  • 主题数据类型-字符串
  • 着力数据类型-列表
  • 主干数据类型-元组
  • 可变、不可变数据类型和hash
  • 主干数据类型-字典
  • 基本数据类型-集结

用过例子来阐明关系运算

  自定义购买iphone7和iphone8的人
    i7 = {'xiaozhang','xiangwang','xiaoli'}
    i8 = {'xiaoli','laozhao','laowang'}

交集 intersection()

# 两个都购买的人
>>> l_p  = i7&i8
>>> l_p
{'xiaoli'}

# 也可以使用
>>> i7
{'xiaoli', 'xiangwang', 'xiaozhang'}
>>> i8
{'xiaoli', 'laozhao', 'laowang'}
>>> i7.intersection(i8)
{'xiaoli'}

差集 difference()

# 只购买iphone7的人
>>> i7.difference(i8)
{'xiangwang', 'xiaozhang'}

# 只购买iphone8的人
>>> i8.difference(i7)
{'laowang', 'laozhao'}

并集 union()

# 购买iphone7和iphone8的人
>>> i7.union(i8)
{'laozhao', 'laowang', 'xiaozhang', 'xiaoli', 'xiangwang'}
>>> i8.union(i7)
{'laozhao', 'laowang', 'xiaozhang', 'xiaoli', 'xiangwang'}

# 也可以使用
>>> i7|i8
{'laozhao', 'laowang', 'xiaozhang', 'xiaoli', 'xiangwang'}

对称差集,把不夹杂的地方抽取来 symmetric_difference

# 可以理解为: 只买了i7和只买了i8的人
>>> i7 = {'xiaozhang','xiangwang','xiaoli'}
>>> i8 = {'xiaoli','laozhao','laowang'}
>>> i7.symmetric_difference(i8)
{'laowang', 'xiaozhang', 'xiangwang', 'laozhao'}

子集

# 可以理解成北京市是中国的子集,而中国是北京市的超集
>>> s = {1,2,3}
>>> s2 = {1,2,3,4,5,6}
>>> s.issubset(s2)
True

# 也可以使用
>>> s2>s
True

超集

print(s,s2)
{1, 2, 3} {1, 2, 3, 4, 5, 6}
s2.issuperset(s)
True

# 也可以使用
>>> s<s2
True

判别五个聚众是或不是不相交 isdisjoint()

set1 = {1,2,3}
set2 = {7,8,9}
set1.isdisjoint(set2)
True

收获差集天公地道新赋值给set1

set1
{1, 2, 3, -1, -2}
set2
{1, 2, 3, 7, 8, 9}
set1.difference(set2)
{-1, -2}
set1.difference_update(set2)
set1
{-1, -2}
set2
{1, 2, 3, 7, 8, 9}

元组的用途

  • 来得的告知外人,此处数据无法改改
  • 数据库连接配置音信等

取余运算

>>> 16%5
1

字符串的定义和成立

字符串是一个有序的字符的聚众,用于存款和储蓄和表示基本的文书新闻,“”“”“高级中学档含有的内部存款和储蓄器称之字符串

创建:

s = 'Hello XiaoYafei!Hello Python!'

集合

复数

复数complex是由实数和虚数组成的。

要打听复数,其实关于复数还索要先通晓虚数。虚数(正是虚假不实的数):平方为复数的数称为虚数。

复数是指能写成如下方式的数a+bi,这里a和b是实数,i是虚数单位(即-1开根)。在复数a+bi中,a称为复数的实部,b称为复数的虚部(虚数是指平方为负数的数),i称为虚数单位。

当虚部等于零时,那一个复数便是实数;当虚部不等于零时,这么些复数称为虚数。

注,虚数部分的假名j大小写都得以。

装水桶法

先把他们表示的值二遍写出来,然后再依据10进制的值把数填到相应岗位,就好了~~~
十进制转二进制的格局同样,只要对照二进制为1的那壹位对应的十进制值相加就足以了。

        128     64      32      16      8       4       2        1

20       0       0       0       1      0       1       0        0   
200      1       1       0       0      1       0       0        0

缘何要用浮点数

浮点数也正是小数,之所以称为浮点数,是因为依照科学记数法表示时,
三个浮点数的小数点地点是可变的,譬喻,
1.23×109和12.3×108是特其他。
浮点数能够用数学写法,如1.23,3.14,-9.01,等等。不过对于极大或十分的小的浮点数,就务须用科学计数法表示,把10用e替代:
1.23*109就是1.23e9,恐怕12.3e8,0.000012能够写成1.2e-5,等等。
大背头和浮点数在管理器内部存款和储蓄的点子是见仁见智的,整数运算永久是可信赖的而浮点数运算则大概会有四舍五入的基值误差。

字典的表征

  • key-value结构
  • key必得可hash,且必得为不可变类型\总得独一
  • 可存放任性几个值\可修改\能够不独一
  • 无序

宗旨数据类型-字典

特性

1.遵照从左往右的一一定义字符集合,下表从0初叶逐项访问,有序

    str      =           hello
    索引                 01234

补充:
1.字符串的单引号和双引号都无计可施裁撤特殊字符的意义,倘使想让引号内具备字符均撤销特殊含义,在指导后边增多r,如:
python name = r'pytho\tn'

  • 动用ctrl加上鼠标左键能够查看源码
class str(object):
    """
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str

    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    """
    def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str

        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

    def casefold(self): # real signature unknown; restored from __doc__
        """
        S.casefold() -> str

        Return a version of S suitable for caseless comparisons.
        """
        return ""

    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str

        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str

        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found, 
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Raises ValueError when the substring is not found.
        """
        return 0

    def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool

        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool

        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool

        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

    def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool

        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool

        Return True if S is a valid identifier according
        to the language definition.

        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

    def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool

        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False

    def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool

        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False

    def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self): # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool

        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False

    def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool

        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str

        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str

        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

    def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().

        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass

    def partition(self, sep): # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)

        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Raises ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)

        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str

        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

    def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str

        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str

        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

    def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str

        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""

    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""

    def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

GBK和GB2312

很鲜明,对于大家的话,能在计算机中显示普通话才是最要害的,可是在刚才ASCII表里连贰个偏旁部首都未有。所以大家须要一张有关中文和数字对应的关系表。从前大家看来,1个字节最多表示257个字符,要管理普通话显明一个字节是远远不足的,所以大家须求采取2个字节来代表,何况还不可能和ASCII编码争辨,所以中中原人民共和国拟定了GB2312编码,用来把粤语编进去。

这就是说此时,又并发了难题:环球由一百各类语言,当国外某些游戏大概电影引到中中原人民共和国来时,那么编码要求怎么管理?

元组的常见操作

索引

ages = (11,22,33,44,55)
ages[0]
11
ages[3]
44

切片

ages
(11, 22, 33, 44, 55)
ages[1:2]
(22,)
ages[1:]
(22, 33, 44, 55)
ages[::2]
(11, 33, 55)

循环

ages
(11, 22, 33, 44, 55)
for i in ages:
… print(i)

11
22
33
44
55

len() 长度

ages
(11, 22, 33, 44, 55)
len(ages)
5

in 包含

ages
(11, 22, 33, 44, 55)
11 in ages
True

末段批注元组的改造

ages
(11, 22, 33, 44, 55)
ages[1] = ‘libaba’
Traceback (most recent call last):
File ““, line 1, in
TypeError: ‘tuple’ object does not support item assignment #立马报错提醒无法修改

字符编码

十进制与二进制之间的更改只可以消除Computer精晓数字的主题材料,那么为文字的话供给怎么让电脑去领会啊?
于是乎就有了一种曲线救国的点子,既然数字能够调换到十进制,那么大家只供给想办法消除文字转变到数字的难题,那么文字不正是足以表示成二进制了吧?
只是文字应该怎么转变来二进制呢? 正是强制转变
大家本人强行约定了叁个表,把文字和数字对应上,那张表就等于是开展了翻译,大家得以拿叁个数字来相比较对应表中的文字,反之亦然。

中央数据类型-元组

hash

  • 就算将轻易长度的字符串,通过散列算法,产生固定长度的出口,该出口正是散列值
  • 这种转移被称为压缩映射,散列值的空中常常远低于输入的空间,区别的输入或然会散列成一样的输出,所以不恐怕从散列值来却东独一输入值
  • 简轻松单的来讲,正是将一种大肆长度的音信压缩到稳固长度的音讯摘要的函数

特征

  • hash值的图谋进程是基于那几个值的部分特点实行测算的,必要被hash值是一定的,由此被hash是不可变的

用途

  • 文本具名
  • md5加密(不能反解)
  • 密码验证

语法

hash(‘xiaoyafei’)
-1204730465301308513

附近操作

字符串是不可变的?

a = ‘xiaoyafei’ #变量的复制,正是将以此变量指向内部存款和储蓄器空间中的地址
id(a) #查看到那儿变量a的空间地址
139742341438256
a = ‘xiaobaba’ #对a实行修改
id(a) #再度查看变量a的上空地址
139742341436848

干什么说字符串是不可变的吧?我们能够很清晰的见到变量a两遍的长空地址并不一样等,是因为在大家修改时,把a指向了另一个内部存款和储蓄器空间地址,而xiaoyafei那些值将会被垃圾回收

swapcase() 小写变大写,大写变小写

str = ‘Hello World’
str.swapcase()
‘hELLO wORLD’

capitalize() 首字母大写,其他全改成小写

str = ‘helLo WORLD’
str.capitalize()
‘Hello world’

casefold() 把大写都全部换来小写

str = ‘HELLO WORLD!’
str.casefold()
‘hello world!’

center() 重临字符串在其中,两侧以字符填充

str = ‘hello world’
str.center(50,’‘)
**
hello world**

count() 总括字符出现的次数

str = ‘abcdfdawadsqasacsasasaa’
str.count(‘a’)
9

#也可以指定从哪开始到哪结束

str.count(‘a’,0,10)
3

endswith() 剖断是或不是以某字符串结尾,再次来到True或False

str = ‘hello world!python’
str.endswith(‘python’)
True
str.endswith(‘hello’)
False

expandtabs() 扩展tab键

a = ‘a\tb’
a
‘a\tb’
print(a)
a b
a.expandtabs(20)
‘a b’

find() 查找,找到则赶回索引,找不到则赶回-1

name = ‘xiaoyafei’
name.find(‘o’)
3
name.find(‘g’)
-1

#也可以规定搜索范围

name.find(‘a’,4,9)
5

format() 格式化字符串

info = ‘my name is {0},i am {1} years old.’
info.format(‘xiaoyafei’,22)
‘my name is xiaoyafei,i am 22 years old.’

#也可以使用变量

info = ‘my name is {name},my age is {age}.’
info.format(name = ‘xiaoyafei’,age=22)
‘my name is xiaoyafei,my age is 22.’

index() 重临索引值,找不到则报错

s = ‘hello tairan and welcome!’
s.index(‘t’)
6
s.index(‘g’)
Traceback (most recent call last):
File ““, line 1, in
ValueError: substring not found

#也可以根据开始和终止位置查找

s
‘hello tairan and welcome!’
s.index(
… ‘a’)
7

isalnum() 判定是还是不是阿拉伯字符(数字和字母)

a = ‘123abc’
a.isalnum()
True
b = ‘123!abc’
b.isalnum()
False

is阿尔法() 剖断是不是只含有字木,不分包数字

a = ‘abc123’
a.isal
a.isalnum( a.isalpha(
a.isalpha()
False
b = ‘abcdefg’
b.isalpha()
True

decimal() 判别是还是不是是整数

a = ‘111’
a.isdecimal()
True

#第二种方法

a.isdigit()
True

isidentifier() 决断字符串的值是否足以行使的变量名

a = ‘111’
a.isidentifier()
False #数字不可能当做变量名
b = ‘Menu’
b.isidentifier()
True

islower() 剖断字符串是还是不是都是小写

str = ‘HelloWorld’
str.islower()
False
str2 = ‘helloworld’
str2.islower()
True

isnumeric() 剖断是还是不是只有数字在内部

a = ‘1233’
a.isnumeric()
True
b = ‘abc123’
b.isnumeric()
False

isspace() 推断是或不是空格

a = ‘ ‘
a.isspace()
True

title() 产生title,即每三个单词的首字母都以大写

str = ‘hello world python tairan ‘
str.title()
‘Hello World Python Tairan ‘

upper() 将字符串全体调换来大写
python >> namew = 'xiaoyafei' >> namew.upper() 'XIAOYAFEI'
join() 把列表产生字符串后,以钦点的字符串来区分列表里的要素

names = [‘lipeng’,’likun’,’lipeng’]
str = ‘—‘
str.join(names)
‘lipeng—likun—lipeng’

ljust() 从左侧起先,总长度相当不够的话用钦赐的字符去顶替

name = ‘xiaoyafei’
name.ljust(50,’‘)
‘xiaoyafei__

lower() 把字符串都造成小写

name = ‘XIAOYAFEI’
name.lower()
‘xiaoyafei’

strip() 去除两侧的空格和换行

str = ‘\n hello world ‘
str.strip()
‘hello world’

# lstrp只去左边不去右边
# rstrip只去右边不去左边

maketrans() 密码表

str_in = ‘1234567890’ #这几个为原来的
str_out = ‘!@#$%^&()’ #这一个是出口后的
table = str.maketrans(str_in,str_out) #将两张表举行对应涉及
s = ‘572428582’ #重新输入的
s.translate(table) #输出后的密码表
‘%&@$@
%*@’

partition() 把全路字符串以投机想要的进展切割

str
‘hello world’
str.partition(‘o’)
(‘hell’, ‘o’, ‘ world’)

replace() 替换,暗中认可全部转移掉

s = ‘hello world,hello tairan’
s.replace(‘llo’,’LLO’)
‘heLLO world,heLLO tairan’

#只更换一次

s
‘hello world,hello tairan’
s.replace(‘llo’,’LLO’,1)
‘heLLO world,hello tairan’

rsplit() 从右边早先将字符串以钦点的字符切割

s
‘hello world,hello tairan’

s.rsplit(‘o’)
[‘hell’, ‘ w’, ‘rld,hell’, ‘ tairan’]

splitlines() 按行来分,格式为列表

str = ‘a\nb\nc\nd\n’
str.splitlines()
[‘a’, ‘b’, ‘c’, ‘d’]

startswith() 判定以钦命字符初始

str
‘hello,xiaoyafei’
str.startswith(‘hel’)
True

zfill() 从左最早,以钦赐字符代替,(左边为原字符串)

str = ‘hello tairan’
str.zfill(50)
‘00000000000000000000000000000000000000hello tairan’

群集的创设

set = {'xiaozhang','laowang','dage'}
有人可能会说了着明明是一个字典,那我们用type()函数试一下
>>> set = {'xiaozhang','laowang','dage'}
>>> type(set)
结果为:class 'set'>
原来当{}里为空就是一个字典,如果有东西就是集合

由三个依旧三个规定的成分所结合的全部叫做会集

会晤中的成分由八个性情

  • 综上说述(成分必得可hash)
  • 互异性(去重)
  • 冬天性(集合中的成分未有前后相继之分)

注意:集合存在的意思就是介于去重和关系运算

ASCII码

ASCII表

ASCII(American Standard Code for Information
Interchange,U.S.A.音信置换标准代码)是依附拉丁字母的一套计算机编码系统,首要用于显示当代匈牙利(Magyarország)语和别的西欧语言。它是现行反革命最通用的单字节编码系统,并一样国际规范ISO/IEC
646。

出于计算机是美国人发明的,因而,最先唯有130个字母被编码到电脑里,也正是深浅写英字母、数字和一部分符号,那些编码表被誉为ASCII编码,举个例子大写字母
A的编码是65,小写字母 z的编码是122。后126个称呼扩展ASCII码。

那以往大家就通晓了上边的假名符号和数字对应的表是早已存在的。那么根据后天有的有些十进制,大家就足以转变到二进制的编码串。
比如:

一个空格对应的数字是0     翻译成二进制就是0(注意字符0和整数0是不同的)
一个对勾√对应的数字是251  翻译成二进制就是11111011

叩问:借使大家要打字与印刷三个空格和三个对勾,写成二进制就应该是[`0011111011],不过难题来了,大家怎么精晓从哪到哪是四个字符呢?聪明的人类就想出了三个消除办法,既然一共就那2五15个字符,那最长的也只是11111111八人,比不上就把装有的二进制都调换来8位的,不足的用0来替换。

那样一来,刚刚的多个空格二个对勾就创作[`000000000000000011111011],读取的时候假诺每回读8个字符就能够驾驭各类字符的二进制值啦。

在这里,[`每一个人0或然1所占的半空中单位为bit(比特)],那是计算机中细小的表示单位。每8个bit组成一个字节,那是Computer最小的囤积单位。

    bit                 位,计算机中最小的表示单位
    8bit = 1bytes       字节,最小的存储单位,1bytes缩写为1B
    1KB = 1024KB
    1MB = 1024KB
    1GB = 1024MB
    1TB = 1024GB
    1PB = 1024TB
    ......

那么,到了前几天学完了ASCII码,作为一名韩文技术员来讲,基本是一揽子了,可是作为一名中华夏族民共和国程序员,是否感觉还少了点什么?

整型

Python中的整数属于int类型,暗中同意用十进制表示,其它也援救二进制,八进制,十六进制表示方法。

列表的开创

list_test = ['张三','李四','xiaoyafei',22]
或
list_test = list(['zhangsan','lisi','wanger'])

二进制与十进制的转移

二进制的第n位表示的十进制值都刚好遵从着2的n次方这些原理

二进制

二进制是测算手艺中运用的一种进制。二进制数由0和1三个数据组成,它的基数为2,进制准则是“逢二进一”,由18世纪德意志联邦共和国数理历史学大师莱布尼兹开掘。当前的微管理器种类应用的大都是二进制系统,数据在处理器中首假设以补码的格局储存的。计算机中的二进制则是一个相当微小的开关,用“开”代表1,“关”代表0。

深拷贝和浅拷贝

这里再一次定义了列表!

# 把list复制给list3
>>> list
['zhangsan', 'xiaoyafei']
>>> list3 = list
>>> id(list)            #查看到列表的ID号是一样的
2661905413128
>>> id(list3)
2661905413128
>>> list[1] = 'lidapeng'    #所以可以理解为这个列表是公用的
>>> list3
['zhangsan', 'lidapeng']
>>> list
['zhangsan', 'lidapeng']

让大家先是来回看下变量:

    name = 'xiaoyafei'      #代表在内存中开辟一个新的空间用来存放这个值xiaoyafei,变量名为name
    name2 = name        #代表着name2指向了这个空间地址,这个空间地址的值是xiaoyafei
    >>> id(name)        #内存空间地址相同,即可证明这一点
    2292157129392
    >>> id(name2)
    2292157129392

那么大家盼望list能和list4分开,那么大家就须求选择copy()函数:

# 此时的list和list2列表是完全独立的
>>> list = ['zhangsan','lisi']
>>> list
['zhangsan', 'lisi']
>>> list2 = list.copy()     #list调用copy()函数,copy给list2
>>> list2
['zhangsan', 'lisi']
>>> list[1] = 'xiaoyafei'
>>> list2
['zhangsan', 'lisi']

# 查看两个列表的ID号
>>> id(list)
2661905413128
>>> id(list2)
2661906326600 

知识点2–浅copy

# 重新定义list和list2函数,然后使用append将list2添加到list中
>>> list = ['zhangsan','lisi','wangwu']
>>> list2 = ['beijing','shanghai','guangzhou']
>>> list.append(list2)
>>> list
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai', 'guangzhou']]

# 这个时候我们使用copy()函数
>>> list3 = list.copy()
>>> list3
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai', 'guangzhou']]
>>> id(list)        #查看内存地址后发现是不一样的,那么我们对list进行修改的话,list3也会修改吗?
1708042040328
>>> id(list3)
1708042953736

# 我们来修改测试一下
>>> list[1] = 'xixihaha'        #对list列表下标为1的元素进行修改,发现 list3没有继续修改
>>> list
['zhangsan', 'xixihaha', 'wangwu', ['beijing', 'shanghai', 'guangzhou']]
>>> list3
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai', 'guangzhou']]

# 让我们再来修改一下看看
>>> list[3][0] = '珠海'
>>> list
['zhangsan', 'xixihaha', 'wangwu', ['珠海', 'shanghai', 'guangzhou']]
>>> list3
['zhangsan', 'lisi', 'wangwu', ['珠海', 'shanghai', 'guangzhou']]
# 奇怪的事情发生了,为什么list3也会跟着修改呢?可刚刚我们测试的时候是没有修改的啊

# 原因就是
>>> id(list[3])     #我们发现在列表中的子列表在内存中的空间地址是一模一样的,难不成会跟着修改呢
1708042061768
>>> id(list3[3])
1708042061768

知识点3–深copy

# 在这里,我们又重新定义了列表
>>> list = ['zhangsan','lisi','wangwu']
>>> list2 = ['beijing','shanghai']
>>> list.append(list2)
>>> list
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai']]

# 如果想使用深copy的话,需要导入python的工具包copy
>>> list
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai']]
>>> import copy     #导入python工具包
>>> list3 = copy.deepcopy(list)
>>> list3
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai']]
>>> id(list)
1255945745416
>>> id(list3)
1255948140680

# 让我们来试一下
>>> list[1] = 'xixihaha'        #对list列表下标为1的元素进行修改,发现list3并无修改
>>> list
['zhangsan', 'xixihaha', 'wangwu', ['beijing', 'shanghai']]
>>> list3
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai']]

# 再来试一下
>>> list[3][0] = '珠海'
>>> list
['zhangsan', 'xixihaha', 'wangwu', ['珠海', 'shanghai']]
>>> list3
['zhangsan', 'lisi', 'wangwu', ['beijing', 'shanghai']]
那么为什么list3没有随着list的改变再修改呢?
原因看下面

深copy和浅copy的区别

  • 浅copy不会另行创立内部存款和储蓄器地址,内容针对从前的空间地址,倘若浅copy对象中有别的子对象,那么在改造这一个子对象的时侯子对象的开始和结果就能够改变
  • 深copy正是新建三个对象重复分配空间地址,复制对象的剧情

那正是说我们得以知晓成,在list这一个列表中,存在着子列表,那么大家对子列表之外的要素举办更动时,另三个对象不会去修改,但是在大家修改子列表的因素的时候,另多少个列表就能够随着修改

着力数据类型-数字

字符串的特点与常用操作

浮点型

浮点数是属于有理数中某一定子集的数的数字代表,在微型Computer中用于近似表示任意有个别实数。具体的说,这一个实数由二个整数或定点数(即尾数)乘以有个别基数(Computer中一般是2)的卡尺头次幂获得,那表示方法类似于基数为10的科学计数法。

python的浮点数便是数学中的小数(有限小数和极端循环小数)

在运算中,整数与浮点数运算的结果也是一个浮点数

divmod

>>> divmod(16,3)
(5, 1)          #5为商,1为余数

至于小数不精准难题

python暗许是二十位精准度,也等于小数点的后13个人,纵然有15个人,但那些准确度依旧越今后越不准的。

第一,那几个难点不是只存在在python中,其余语言也会有平等的题目

附带,小数不精准是因为在转变到二进制的进度中会出现极度循环的情状,在约省的时候就能够并发错误。

比如:11.2的小数部分0.2退换为2进制则是非常循环的00110011001100110011…

单精度在积存的时候用23bit来贮存在那个尾数部分(前面9比特仓库储存指数和符号);同样0.6也是最棒循环的;

那边有一个标题,正是当我们的计量必要越来越高的精度(超越十三人数)的事态下怎么办呢?

#这里需要借助decimal模块的getcontext()和Decimal()方法
>> a = 3.141592653513651054608317828332
>>> a
3.141592653513651
>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
>>> getcontext().prec = 50      #将小数点后的尾数修改到50
>>> a = Decimal(1)/Decimal(3)   #在分数计算中结果正确,如果直接定义超长精度小数不会准确
>>> a
Decimal('0.33333333333333333333333333333333333333333333333333')
>>> a = 3.141592653513651054608317828332
>>> a
3.141592653513651
>>> Decimal(a)
Decimal('3.141592653513650912344701282563619315624237060546875')

相关文章