Python数据类型

数据类型

Python的数据属于某一种类型,相同类型的数据可以做运算,不同类型的数据运算会报错

# input()函数读入的数据一定是字符类型
>>> n = input('number: ')
number: 10
>>> n + 5        # 错误,字符串不能和数字相加
>>> int(n) + 5   # int函数将字符串'10'转成数字10
15
>>> n + str(5)   # str函数可以将各种对象转成字符串
'105'

1)数字

基本数字类型
  • int:有符号整数
  • bool:布尔值
    • False: 0
    • True: 1
  • float:浮点数
  • complex:复数
数字表示方式
  • python默认以十进制数显示(没有前缀)
  • 数字以0o或0O开头表示为8进制数
  • 数字以0x或0X开头表示16进制数
  • 数字以0b或0B开头表示2进制数

2)字符串

  • python中字符串被定义为引号之间的字符集合
  • python支持使用成对的单引号或双引号无论单引号,还是双引号,表示的意义相同
  • python还支持三引号(三个连续的单引号或者双引号),可以用来包含特殊字符
  • python不区分字符和字符串
>>> s1 = """hello
... nice
... ban"""
>>> print(s1)
hello
nice
ban
>>> s1
'hello\nnice\nban'
>>> s2 = "tom\njerry\npeppa"
>>> print(s2)
tom
jerry
peppa
字符串操作
>>> s1 = 'python'
>>> len(s1)     # 求长度
6
>>> s1[0]       # 下标从0开始
'p'
>>> s1[5]
'n'
>>> s1[6]       # 报错,下标没有6
>>> s1[-1]      # 下标为负,表示从右开始取
'n'
>>> s1[-6]
'p'
>>> s1[2:4]     # 取切片,起始下标包含,结束下标不包含
'th'
>>> s1[2:6]     # 取切片时,下标越界不报错
'thon'
>>> s1[2:6000]
'thon'
>>> s1[2:]      # 结束下标不指定,取到结尾
'thon'
>>> s1[:2]      # 起始下标不指定,从开头取
'py'
>>> s1[:]
'python'
>>> s1[::2]     # 2表示步长值
'pto'
>>> s1[1::2]
'yhn'
>>> s1[::-1]    # 步长为负,表示从右向左取
'nohtyp'

>>> 't' in s1   # 't'在s1中吗?
True
>>> 'th' in s1  # 'th'在s1中吗?
True
>>> 'to' in s1  # 'to'在s1中吗?
False           # to在字符串中不连续,为假
>>> 'to' not in s1  # 'to'不在s1中吗?
True
>>> 'hello' + 'world'   # 字符串拼接
'helloworld'
>>> '*' * 50    # 字符串重得50次
'**************************************************'
>>> s1 * 5
格式化操作符
格式化字符转换方式
%c转换成字符
%s优先用str函数进行字符串转换
%d / %i转成有符号十进制数
%o转成无符号八进制数
%x转成无符号十六进制数
%e/%e转成科学计数法
%f/%F转成浮点数转换方式
# 基本形式:
'' % ()
# 引号中可以使用%s / %d 等占位,()中对应的数据支替代引号中的占位符
# 如果引号中只有一个占位符,引号后面的()可以省略
>>> '%s is %s years old' % ('tom', 20)
'tom is 20 years old'
>>> 'Hello %s' % ('jerry')
'Hello jerry'
>>> 'Hello %s' % 'jerry'
'Hello jerry'

>>> '%s is %d years old' % ('tom', 20)  # %d表示10进制整数
'tom is 20 years old'
>>> '%d is %d years old' % ('tom', 20)  # 报错,因为tom转不成整数
>>> '%s is %d years old' % ('tom', 20.5)
'tom is 20 years old'
辅助指令作用
*定义宽度或者小数点精度
-左对齐
+在正数前面显示加号
<sp>在正数前面显示空格
#在八进制数前面显示零0,在十六进制前面显示Ox或者oX’
0显示的数字前面填充0而不是默认的空格
  • 字符串格式化还可以使用format方法
>>> '{} is {} years old'.format('tom', 20)
'tom is 20 years old'
>>> '{} is {} years old'.format('tom', 20)
'tom is 20 years old'
>>> '{1} is {0} years old'.format(20, 'tom')
'tom is 20 years old'
  • 原始字符串,也叫真实字符串
>>> win_path = 'c:\temp'
>>> print(win_path)      # \t被转义成tab
c:      emp
>>> wpath = r'c:\temp'   # r后面字符串的内容都表示其本身含义
>>> print(wpath)
c:\temp
>>> wpath
'c:\\temp'
>>> win_path = 'c:\\temp'
>>> print(win_path)
c:\temp
  • 方法
>>> s1 = 'HELLO world'
>>> s1.upper()
'HELLO WORLD'
>>> s1.lower()
'hello world'
>>> s1.center(50)       # 居中,总宽度50
'                   HELLO world                    '
>>> s1.center(50, '#')  # 使用#填充
'###################HELLO world####################'
>>> s1.ljust(50, '*')   # 左对齐
'HELLO world***************************************'
>>> s1.rjust(50)        # 右对齐
'                                       HELLO world'
>>> s2 = '    hello world\n'
>>> s2.strip()          # 消除字符串两端空白字符
'hello world'
>>> s2.lstrip()         # 消除字符串左端空白字符
'hello world\n'
>>> s2.rstrip()         # 消除字符串右端空白字符
'    hello world'
  1. string.capitalize():把字符串的第一个字符大写
  2. string.center(width):返回一个原字符串居中,并 使用空格填充至长度 width的新字符串
  3. string.count(str,beg=0,end=len(string)):返回str在 string里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数
  4. string.endswith(obj,beg=0,end=len(string): 检查字符串是否以obj结束,如果beg或者end指定则检查指定的范围内是否以obj结束,如果是,返回True, 否则返回 False
  5. string.islower():如果 string中包含至少一个区分大小写的字符,并且所有这些字符都是小写,则返回True,否则返回 False
  6. string.strip():删除string 字符串两端的空白
  7. string.upper():转换string中的小写字母为大写
  8. string.split(str="",num=string.count(str)):以str为分隔符切片string,如果num有指定值,则仅分隔num个子字符串

3)列表

  • 可以将列表当成普通的“数组”,它能保存任意数量任意类型的 python对象
  • 像字符串一样,列表也支持下标和切片操作
  • 列表中的项目可以改变
  • 属于容器、可变、顺序类型
>>> l1 = [10, 15, 'tom', 'jerry', [1, 2, 3]]
>>> l1 = [10, 15, 'tom', 'jerry', [1, 2, 3]]
>>> len(l1)
5
>>> l1[0]
10
>>> l1[-1]
[1, 2, 3]
>>> l1[2:4]
['tom', 'jerry']
>>> 'tom' in l1
True
>>> 2 in l1         # 2是列表的一项吗?
False
>>> l1[-1] = 100    # 把列表最后一项重新赋值
>>> l1
[10, 15, 'tom', 'jerry', 100]
>>> l1 + 20         # 不同类型的数据不能直接运算
>>> l1 + [20]
[10, 15, 'tom', 'jerry', 100, 20]
>>> l1 * 2
[10, 15, 'tom', 'jerry', 100, 10, 15, 'tom', 'jerry', 100]
>>> l1     # 拼接和重复,列表本身不会改变
[10, 15, 'tom', 'jerry', 100]
>>> l1 = [10, 8, 20, 10, 35, 2]
>>> l1[0] = 20
>>> l1[1:3] = [10, 20, 30, 40]   # 批量替换
>>> l1
[20, 10, 20, 30, 40, 10, 35, 2]
>>> l1[1:1]
[]
>>> l1[1:1] = [100, 200]    #批量插入
>>> l1
[20, 100, 200, 10, 20, 30, 40, 10, 35, 2]
  • 方法
函数作用
list.append(obj)向列表中追加一个obj
list.extend(seq)把序列seq的内容添加到列表中
list.count(obj)返回一个对象obj在列表中出现的次数
list.index(obj)返回ob对象的下标
list.insert(index,obj)在索引量为index的位置插入对象obj
list.reverse()原地翻转列表
list.sort()排序
list.remove(obj)删除列表中第一个obj
list.pop(index)弹出(删除并返回值)指定下标的obj,index默认为-1
>>> l1.append([1, 2, 3])  # 将列表[1, 2, 3]追加到列表
>>> l1
[20, 100, 200, 10, 20, 30, 40, 10, 35, 2, 20, [1, 2, 3]]
>>> l1.extend([1, 2, 3])  # 1, 2, 3作为三个单独的项目追加入列表
>>> l1
[20, 100, 20, 200, 10, 20, 30, 40, 10, 35, 2, 20, [1, 2, 3], 1, 2, 3]
>>> l1.insert(2, 20)      # 向下标为2的位置插入20
>>> l1.count(20)          # 统计20出现的次数
4
>>> l1.index(20)          # 返回第一个20的下标
0
>>> l1.index(20,1)		  # 从下标为1的位置向后查找20的下标
>>> l1.remove(20)         # 删除第1个20
>>> l1
[100, 20, 200, 10, 20, 30, 40, 10, 35, 2, 20, [1, 2, 3], 1, 2, 3]
>>> l1.pop()              # 默认弹出最后一项(删除并返回值)
3
# l1.remove()和l1.pop()都是函数调用,remove没有返回值,pop有
>>> a = l1.remove(20)
>>> print(a)
None
>>> b = l1.pop()
>>> b
2
>>> l1.pop(-2)           # 弹出下标为-2的元素
[1, 2, 3]
>>> l1
[100, 200, 10, 20, 30, 40, 10, 35, 2, 20, 1]
>>> l1.sort()            # 排序
>>> l1
[1, 2, 10, 10, 20, 20, 30, 35, 40, 100, 200]
>>> l1.reverse()         # 翻转
>>> l1
[200, 100, 40, 35, 30, 20, 20, 10, 10, 2, 1]

>>> l2 = l1              # l1和l2指向相同的内存地址
>>> l2
[200, 100, 40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l2.pop(0)            # 改动l2也会影响l1
200
>>> l2
[100, 40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l1
[100, 40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l3 = l1.copy()       # 将l1的值赋值给l3,但是l3采用不同的内存地址
>>> l3
[100, 40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l3.pop(0)
100
>>> l3
[40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l1
[100, 40, 35, 30, 20, 20, 10, 10, 2, 1]
>>> l3.clear()          # 清空列表
>>> l3
[]

4)元组

  • 可以认为元组是“静态”的列表
  • 元组一旦定义,不可改变
>>> t1 = (10, 15, 'tom', 'jerry', 100, 15)
>>> len(t1)
6
>>> t1[0]
10
>>> t1[2:4]
('tom', 'jerry')
>>> t1[0] = 20    # 报错
  • 属于容器、不可变、顺序类型
>>> t1 = (22, 10, 3, 20)
>>> t1.count(10)   # 统计10出现的次数
1
>>> t1.index(3)    # 返回3的下标
2
  • 如果元组只有一项,必须在元素后面加逗号,否则它不是元组
>>> t2 = (10)
>>> t2
10
>>> type(t2)      # t2是整数,不是元组
<class 'int'>
>>> t3 = (10,)    # 定义单元素元组
>>> type(t3)
<class 'tuple'>
>>> len(t3)
1
>>> t3
(10,)

5)字典

  • 采用key:val的形式存储各项
  • 属于容器、可变、映射
  • 字典的key是唯一的,不能出现多于一次
  • 字典的key必须时不可变的(数字、字符串、元组)
>>> d1 = {'name': 'tom', 'age': 20}
>>> len(d1)
2
>>> d1['name']     # 通过key取出val
'tom'
>>> 'tom' in d1    # tom是字典的key吗?
False
>>> 'name' in d1
True
  • 定义字典:
>>> d1 = {'name': 'tom', 'name': 'jerry', 'age': 20}
>>> d1
{'name': 'jerry', 'age': 20}
>>> d2 = dict([('name', 'tom'), ('age', 20), ('email', 'tom@xxx.cn')])
>>> d2
{'name': 'tom', 'age': 20, 'email': 'tom@tedu.cn'}
>>> d3 = {}.fromkeys(['tom', 'jerry', 'bob', 'alice'], 20)   #创建具有相同值的字典
>>> d3
{'tom': 20, 'jerry': 20, 'bob': 20, 'alice': 20}
>>> len(d2)
3
>>> 'tom' in d2     # tom是字典的key吗?
False
>>> 'name' in d2
True
>>> for k in d2:    # 遍历字典
...   print(k, d2[k])
# 通过key进行赋值,如果key不在字典里则加入新值;如果key在字典里,则修改
>>> d2['age'] = 25
>>> d2
{'name': 'tom', 'age': 25, 'email': 'tom@xxx.cn'}
>>> d2['phone'] = '15012345678'
>>> d2
{'name': 'tom', 'age': 25, 'email': 'tom@xxx.cn', 'phone': '15012345678'}
>>> del d2['phone']   # del是关键字,可以删除各种对象,但是不常用
>>> d2
{'name': 'tom', 'age': 25, 'email': 'tom@tedu.cn'}
  • 方法
# 字典中,最重要的方法是get
>>> d2
{'name': 'tom', 'age': 25, 'email': 'tom@tedu.cn'}
>>> user = d2.get('name')   # 通过key来get值
>>> user
'tom'
>>> password = d2.get('password')  # 字典中没有key返回None
>>> print(password)
None
>>> email = d2.get('email', 'not found')  # 获取email的值,没有则返回not found
>>> password = d2.get('password', 'not found')
>>> email
'tom@xxx.cn'
>>> password
'not found'
>>> d2.keys()    # 返回所有的key
dict_keys(['name', 'age', 'email'])
>>> d2.values()  # 返回所有的value
dict_values(['tom', 25, 'tom@tedu.cn'])
>>> d2.items()   # 返回所有的(key,value)
dict_items([('name', 'tom'), ('age', 25), ('email', 'tom@tedu.cn')])
>>> list(d2.items())
[('name', 'tom'), ('age', 25), ('email', 'tom@tedu.cn')]
>>> d2.pop('email')    # 通过key,弹出数据项
'tom@tedu.cn'
>>> d2
{'name': 'tom', 'age': 25}
>>> help(d2.popitem)   # 查看d2.popitem的帮助
>>> d2.update({'qq': '132523452', 'address': 'shijiazhuang'})  # 批量添加数据
>>> d2
{'name': 'tom', 'age': 25, 'qq': '132523452', 'address': 'shijiazhuang'}

6)集合

  • 集合由不同元素构成的
  • 集合元素必须是不可变对象
  • 集合没有顺序
  • 集合就像是一个无值的字典
  • 可变集合是set,不可变集合是frozenset
>>> s1 = {'tom', 'jerry', 1, 20}
>>> s1
{1, 'tom', 'jerry', 20}
>>> type(s1)
<class 'set'>
>>> len(s1)
4
>>> for data in s1:
...   print(data)
>>> s2 = set('abc')
>>> s2
{'a', 'b', 'c'}
>>> s3 = set('bcd')
>>> s3
{'b', 'c', 'd'}
>>> s2 & s3     # 取交集
{'b', 'c'}
>>> s2 | s3     # 取并集
{'a', 'b', 'c', 'd'}
>>> s2 - s3     # 取差补,s2中有s3中没有的元素
{'a'}
>>> s3 - s2
{'d'}
  • 方法
>>> s1.add(200)    # 增加元素
>>> s1
{1, 200, 'tom', 20, 'jerry'}
>>> s1.pop()       # 随机弹出一项
1
>>> s1.remove(20)
>>> s1
{200, 'tom', 'jerry'}
>>> s1.update([100, 200, 300])    # 批量增加数据
>>> s1
{100, 200, 'tom', 300, 'jerry'}
>>> s2.intersection(s3)   # s2 & s3
{'b', 'c'}
>>> s2.union(s3)          # s2 | s3
{'a', 'b', 'c', 'd'}
>>> s2.difference(s3)     # s2 - s3
{'a'}
>>> s4 = {100, 200}
>>> s4.issubset(s1)       # s4是s1的子集吗?
True
>>> s1.issuperset(s4)     # s1是s4的超集吗?
True
  • 集合常用于去重
>>> from random import randint
>>> nums = [randint(1, 50) for i in range(20)]
>>> set(nums)
{32, 3, 35, 8, 13, 46, 49, 17, 20, 22, 23, 25, 30, 31}
>>> nums2 = list(set(nums))
>>> nums2
[32, 3, 35, 8, 13, 46, 49, 17, 20, 22, 23, 25, 30, 31]
  • 案例:取出两个文件不同的内容
    web服务每天产生大量的日志,每天的日志文件500万行以上。日志中存储了客户端访问web服务的哪个url,每天的url提取到一个文件中,如a.log / b.log,获取哪些url是今天新访问的
# 找出mima2中有,mima1中没有的行
[root@localhost day05]# cp /etc/passwd /tmp/mima1
[root@localhost day05]# cp /etc/passwd /tmp/mima2
[root@localhost day05]# vim /tmp/mima2  # 修改,使它与mima1不一样
>>> with open('/tmp/mima1') as fobj:
...   s1 = set(fobj)   # 把文件的每一行作为集合元素
>>> with open('/tmp/mima2') as fobj:
...   s2 = set(fobj)
>>> s2 - s1
{'chi le ma?\n', 'hello world!\n'}
>>> with open('/tmp/mima3', 'w') as fobj:
...   fobj.writelines(s2 - s1)
[root@localhost day05]# cat /tmp/mima3

数据类型分类

1)按存储模型分类
  • 标量:数字、字符串
  • 容器:元组、列表、字典
2)按更新模型分类
  • 可变:列表、字典
  • 不可变:数字、字符串、元组
>>> l1 = [1, 2, 3]
>>> s1 = 'python'
>>> l1[0] = 10
>>> s1[0] = 'P'    # 报错,因为字符串不可变
>>> s1 = 'Python'  # 字符串重新赋值,才能把第一个字符改掉

>>> l1
[10, 2, 3]
>>> l2 = l1
>>> l2
[10, 2, 3]
>>> l2.append(100)
>>> l2
[10, 2, 3, 100]
>>> l1
[10, 2, 3, 100]
3)按访问模型分类
  • 直接访问:数字
  • 顺序访问:字符串、列表、元组
  • 映射访问:字典

序列(字符串、列表、元组)

序列操作符作用
seq[ind]获得下表为ind的元素
seq[ind1:ind2]获得下标从ind1到ind2之间的元素集合
seq * expr序列重复expr次
seq1 + seq2连接序列seq1和seq2
obj in seq判断obj元素是否在seq中
obj not in seq判断obj元素是否不包含在seq中
  • 内建函数:
函数含义
list()把可迭代对象转换为列表
str()把对象转换成字符串
tuple()把一个可迭代对象转换成一个元组对象
len()返回对象的长度
enumerate()接收一个可迭代对象作为参数,返回enumerate参数
reversed()接受一个序列作为参数,返回一个逆序的序列
sorted()接受一个可迭代对象作为参数,返回一个有序的列表
# sorted用于排序,但是不改变对象本身
>>> from random import randint
>>> nums = [randint(1, 100) for i in range(10)]
>>> nums
[32, 51, 3, 96, 32, 28, 19, 47, 34, 60]
>>> a = sorted(nums)
>>> a
[3, 19, 28, 32, 32, 34, 47, 51, 60, 96]

# reverse用于翻转对象,但是不改变对象本身
>>> for i in reversed(nums):
...   print(i)

# enumerate用于返回序列对象的下标和值
>>> enumerate(nums)
<enumerate object at 0x7f615dd568b8>
>>> list(enumerate(nums))
>>> for data in enumerate(nums):
...   print(data)
...
(0, 32)
(1, 51)
(2, 3)
(3, 96)
(4, 32)
(5, 28)
(6, 19)
(7, 47)
(8, 34)
(9, 60)
>>> for data in enumerate(nums):
...   print(data[0], data[1])
...
0 32
1 51
2 3
3 96
4 32
5 28
6 19
7 47
8 34
9 60
>>> for a, b in enumerate(nums):
...   print(a, b)
...
0 32
1 51
2 3
3 96
4 32
5 28
6 19
7 47
8 34
9 60

排序

  • 字典没有顺序,如果为字典排序,需要先将字典转成序列对象
  • 复杂列表排序:根据列表中元组的最后一项排序
    • 列表的sort方法接受一个名为key的变量。 help(list.sort)
    • key变量是一个函数。该函数作用于每个列表项,将列表项作为key函数的参数,key函数的返回值作为排序依据
>>> d1 = {'172.40.58.150': 10, '172.40.58.124': 6, '172.40.58.101': 10, '127.0.0.1': 121, '192.168.4.254': 103, '192.168.2.254': 110, '201.1.1.254': 173, '201.1.2.254': 119, '172.40.0.54': 391, '172.40.50.116': 244}
>>> l1 = list(d1.items())
>>> l1
[('172.40.58.150', 10), ('172.40.58.124', 6), ('172.40.58.101', 10), ('127.0.0.1', 121), ('192.168.4.254', 103), ('192.168.2.254', 110), ('201.1.1.254', 173), ('201.1.2.254', 119), ('172.40.0.54', 391), ('172.40.50.116', 244)]
>>> def get_last(seq):
...   return seq[-1]
...
>>> l1.sort(key=get_last, reverse=True)
>>> l1
[('172.40.0.54', 391), ('172.40.50.116', 244), ('201.1.1.254', 173), ('127.0.0.1', 121), ('201.1.2.254', 119), ('192.168.2.254', 110), ('192.168.4.254', 103), ('172.40.58.150', 10), ('172.40.58.101', 10), ('172.40.58.124', 6)]

# 因为上面的get_last函数非常简单,所以可以使用匿名函数替代它
>>> l1.sort(key=lambda seq: seq[-1], reverse=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值