Python的6种内置对象

1 变量与对象的关系

1.1 引用关系

a = 3  #变量a引用了3这个对象,a为变量,3为对象

1.2 变量对调

a = 3
b = 4
a,b = b,a #这个对调在JAVA等语言中实现会麻烦一些

1.3 变量命名:英文状态下划线

my_book = "Python入门"

1.4 确认对象类型:type函数

a = "你好"
print(type(a))
<class 'str'>

1.5 确认对象唯一性:id函数

3和3.0的内存代码不一样

print(id(3))
140725520925008
print(id(3.0))
2162749522896

1.6 Help函数调出帮助文档

help(id)
Help on built-in function id in module builtins:
id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.

备注:pycharm在控制台内输入可以进入类似与IDLE的交互模式(边写边运行)

2 整数、浮点数

2.1 分类

整数:int
浮点数:float

2.2 四则运算

进制转换:0.1+0.2不等于0.3,计算进行数值运算,把十进制转换成二进制进行计算,但转换过程没法完全转换

0.1+0.2
0.30000000000000004

可以使用round函数进行四舍五入

round(0.1+0.2,2) #round函数,取两位小数
0.3

help(round)
Help on built-in function round in module builtins:
round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

但round也不能解决一切,比如下面也是进制问题。

round(1.2345,3)
1.234

2 字符串

2.1 字符编码

字符编码:字符不能被电脑处理,要先转换成二进制

ord('a')
97 #十进制
bin(97)
'0b1100001' #二进制

乱码:美国的ascii码定义了128个字符,用于英语语言。各国为适配不同的语言,形成不同的字符编码,相互之间产生乱码。
Unicode:统一编码标准,又称统一码、万国码
UTF-8:目前普遍采用的Unicode编码

import sys 
sys.getdefaultencoding() #查询当前计算机的默认编码
'utf-8'

2.2 字符串

定义字符串,一对单/双引号

a = '你好'
b = "你好"

字符串与数字转换

int('250') #字符串转整数
250
str(250) #整数转字符串
'250'

转义:解决引号问题

'what's your name?' #多个引号会报错
  File "<input>", line 1
    'what's your name?'
          ^
SyntaxError: invalid syntax
'what\'s your name?' #加入\转义符号则正常
"what's your name?"

2.3 序列

定义:有序排列的对象,字符串只是序列的一种
字符串的两则运算

m = "python"
n = "book"
m+n #加法运算
'pythonbook'
m*3 #乘法运算
'pythonpythonpython'

得到字符串长度

len(m)
6

判断字符是否在字符串内

"p" in m
True

2.4 索引和切片

从左开始第一个字符是0,空格也是字符

r = "python book"
len(r)
11 #空格也计算字符长度
r[0] #得到索引为0的字符
'p'
r[-1] #得到索引为右边第一个的字符
'k'
r[0:3] #切片,包前不包后,对应0,1,2
'pyt'
r[1:9:2] #设置步长为1(默认)
'ython bo'
r[1:9:2] #设置步长为2
'yhnb'
r[1:] #从1到结尾
'ython book'
r[:] #从头到尾
'python book'
r[::-1] #步长为负,展示全部
'koob nohtyp'
r[8:-10:-2]
'o ot'

2.5 内置函数:input和print

在这里插入图片描述

2.6 字符串的常用属性和方法

在这里插入图片描述

2.7 字符串的格式化输出

python format格式化函数

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
>>>a = "i love python"
>>>a.split(" ") #用空格切分字符串
['i', 'love', 'python']
>>>lst = a.split(" ")
>>>lst
['i', 'love', 'python']
>>>"-".join(lst)
'i-love-python'
>>>"i like {0} and {1}".format("kiki","pupu")
'i like kiki and pupu'
>>>"i like {0:10} and {1:>15}".format("kiki","pupu")
'i like kiki       and            pupu'
>>>"i like {0:^10} and {1:>15}".format("kiki","pupu")
'i like    kiki    and            pupu'
>>>"she is {0:4d} year old and {1:.1f}m in height".format(28,1.68)
 #4d表示4个字符长度,d表示整数,.1f表示.1取以为小数,f是浮点数
'she is   28 year old and 1.7m in height'

3 列表

定义空列表的两种方式

>>>lst = [] 一般用lst定义列表,免得和list重复
>>>list()
[]
>>>str() #定义空字符串
''
>>>int() #定义空整数,得到0
0
>>>float() #定义空浮点数,得到0.0
0.0

列表特点:任何类型、序列、元素可修改。列表既是序列也是容器
列表是个框,什么都能装

lst = [0,1,3.12,"hello",[]]

列表和字符串相似,都是序列,有序,可重复,可索引切片
不同顺序的列表的id不同

>>>lst1 =[2,3]
>>>lst2 =[3,2]
>>>id(lst1)
140214045112192
>>>id(lst2)
140214311365760

索引序列

>>>lst1 =["a","b","c","d"]
>>>lst1[0:2]
["a","b"]

列表元素可替换,字符串不可替换

>>>lst1 =["a","b","c","d"]
>>>lst1[0]="kiki"
>>>lst1
["kiki","b","c","d"]

列表的基本操作与字符串一致)

>>>lst1=[1,2,3]
>>>lst2=[5,6,7]
>>>lst1+lst2
[1, 2, 3, 5, 6, 7]
>>>lst1*2
[1, 2, 3, 1, 2, 3]
>>>len(lst1)
3
>>>3 in lst1
True

3.2 列表的方法

列表这个框,在内存中创建了就确定了,增删元素不会影响内存地址

3.2.1 增加的方法

append、insert、extend(针对可迭代对象iterable)

>>>lst = [1,2,3,4]
[1,2,3,4]
>>>id(lst)
140174582142448
>>>lst.append("haha") 
[1,2,3,4,"haha"]
>>>id(lst)
140174582142448 #元素增加,内存地址不变,没有返回值
>>>r = lst.append("haha") #不返回值,因此r为空
>>>print(r)
None 

help(lst.insert)
Help on built-in function insert:
insert(index, object, /) method of builtins.list instance
    Insert object before index. #在指引索引前插入object对象

help(list.extend)
Help on method_descriptor:
extend(self, iterable, /)
    Extend list by appending elements from the iterable. #插入可迭代对象,如字符串或者列表里的对象

append和extend两者区别
在这里插入图片描述

3.2.2 删除

remove(删除第一个指定的值、pop(删除指定索引并返回对应值)
在这里插入图片描述

3.3 比较列表与字符串

相同点:都是序列,有索引和切片
区别:列表是容器类对象,可变;字符串不可变

4 元组

元括号

t = (1,2,3,[2,3,4],"python")
<class 'tuple'>

元组内只有一个元素要加逗号,否则就不是元组
[1,]

>>>t = (1)
>>>type(t)
<class 'int'>
>>>t=(1,)
>>>type(t)
<class 'tuple'>

元组也是序列,有索引与切片
元组与列表最大的区别是元组的对象不可修改,元组不可变对象
要转化元组的内容,可以先转为列表,修改,再转回元组

比较元组与列表
1、元组不可变
2、元组运算速度快
3、两者都是容器类、序列类对象

5 字典

5.1 字典的定义

d = {}
type(d)
<class 'dict'>

字典创建的是映射关系,{a:b,c:d},
键值对,键(key):值(value),键不可重复,不可是列表(可变对象),值没有限制

d = {"name":"rhino","age":28,"city":"beijing"}

5.2 字典的方法

创建键值对的方法

>>>dict(a=1,b=2,c=3}
{'a': 1, 'b': 2, 'c': 3}

字典没有索引,但方法与索引接近

>>>d = dict(a=1,b=2,c=3}
>>>d['a']
'1'

键值对可以减少(del),替换,in(仅检索键)
创建键值对的方式不止用等号建立,还可以用元组的方法

>>>d = dict([('a',1),('lang','python')])
>>>d
{'a': 1, 'lang': 'python'}
>>>d['a']
1
>>>d['b'] #将会报错并停止,因为键没在里面,get和setdefault为解决的两种方法
>>>d.get('b') #这种方法不会报错
>>>d.get('b','hello') #如果没有b键,就返回‘hello’
>>>help(d.get) #如果键存在返回,不存在返回none,但不会新增键值对
>>>d.setdefault('b') #不存在则新建默认值
{'a': 1, 'lang': 'python','b'=None}

d.update([('c',1),('d','python')]) #新增元素方法1
d1 = {'city':'moscow'}
d.update(d1) #新增元素方法2

删除则用pop和del

5.3 比较字典和列表

1 字典不是序列,没有索引
2 两者都是容器类对象
3 两者都是可变对象
4 python3.6开始,字典也有顺序

6 集合

定义集合,内部元素只能为不可变对象,如果里面放入列表,就会报错

特点:无序性

6.1可变集合

定义可变集合

s = set([1,2,3,4,2,1,4])
s = {2,34,533,}
s.pop() #删除内容1
s.remove() #删除内容2
s.discard() #删除内容3

6.2 不可变集合

定义不可变集合

s = frozenset([1,2,3,4,2,1,4]) #没有add,remove等功能

6.3 集合的特点

字典、列表、集合都有copy
shallow copy浅拷贝

>>>b1 = ['name',3,1020]
>>>b2 = b1.copy()
>>>id(b1)
140461270394832
>>>id(b2)
140461270219904
>>>b1 is b2
False #拷贝的列表不同
>>>b1[0] is b1[0]
True #拷贝的列表内的元素相同

c1 = [1,2,'s',['a','b','c']]
c2 = c1.copy()
c1[3][2] = 'hahah'
c1
[1, 2, 's', ['a', 'b', 'hahah']]
c2
[1, 2, 's', ['a', 'b', 'hahah']] #浅拷贝第二层不变
c1[2] = 'rhino'
c2
[1, 2, 's', ['a', 'b', 'hahah']] #前拷贝第一层变化

浅拷贝只拷贝第一层,藕断丝连;深拷贝deepcopy才可以拷所有层,拷贝对象完全独立

列表 []
字段 {key:value; }

集合和字典的唯一区别仅在于没有存储对应的value

list=[1,2,3]
list=[ ]            # 定义空列表
t=(1,2,3)
t=( )                 # 定义空元组
d={'user':['user1','user2']}
d={}       # 定义空字典
s={1,2,3,4}
s=set([ ])      # 定义空集合

7 案例

7.1 编写程序,根据输入的半径,求圆的面积

# coding:utf-8
'''
例1:编写程序,根据输入的半径,计算圆的面积。
'''

import math

r = float(input("Enter the radius of circle:"))
area = math.pi*r*r

print("The area is :",round(area,2))

7.2 编写程序,利用“凯撒密码”方案,实现对用户输入文字的加密操作。

letter = input("Please input an English letter:")
n = 3
pwd = ord(letter) + n
pwd_letter = chr(pwd)
print(letter, "==>", pwd_letter) #要加空格,否则要报错missing whitespace 

7.3 编写程序,实现对输入字符串的大小写字母翻转操作。

word = input("Please input an English word:")
new_lst = []
for i in word:
    if i.islower():  #如果是小写
        new_lst.append(i.upper())   #转换为大写,并追加到列表中
    else:
        new_lst.append(i.lower())   #转换为小写,并追加到列表中
new_word = "".join(new_lst)   #以空字符串作为连接词将列表连接起来
print(word, "==>", new_word)

《Python大学实用教程》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值