标准数据类型
Python3 中有六个标准的数据类型:
- Number(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Set(集合)
- Dictionary(字典)
Python3 的六个标准数据类型中:
- 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组)
- 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)
Python中的进制表示
>>> 0b10 #表示二进制前面要加上 0b
2
>>> 0b11
3
>>> 0o10 #八进制
8
>>> 0x10 #十六进制
16
进制转化
>>> bin(10) #bin函数:将任意进制转化为二进制
'0b1010'
>>> bin(0o7)
'0b111'
>>> bin(0xE)
'0b1110'
>>> int(0o10) #int函数:向十进制转化
8
>>> hex(32) #hex函数:向16进制转化
'0x20'
>>> hex(0o10)
'0x8'
>>> oct(0b1000) #oct函数:向八进制转化
'0o10'
Number(数字)
Python3 支持 int、float、bool、complex(复数)。
在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long;同时也没有double,不存在单精度、双精度,只有float表示小数
数值运算如下:
>>> 1
1
>>> type(1)
<class 'int'>
>>> type(1*1)
<class 'int'>
>>> type(1/1) ##除法,结果为float
<class 'float'>
>>> type(1//1) ##整除,结果为int型,向下取整
<class 'int'>
>>> 1 / 2
0.5
>>> 1/2
0.5
>>> 1//2
0
>>> 2 ** 5 ##乘方
32
注意:
在混合计算时,Python会把整型转换成为浮点数
Python可以同时为多个变量赋值,如a, b = 1, 2
内置的 type() 函数可以用来查询变量所指的对象类型
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
此外还可以用 isinstance 来判断:
>>>a = 111
>>> isinstance(a, int)
True
isinstance 和 type 的区别在于:
- type()不会认为子类是一种父类类型。
- isinstance()会认为子类是一种父类类型。
bool类型
数字的情况下:非0的数均为True,只有0是false(任意进制下均是false)
>>> type(True)
<class 'bool'>
>>> bool(1)
True
>>> bool(0)
False
>>> bool(2)
True
>>> bool(2.33)
True
>>> bool(-2.44)
True
对于其他类型的空值,也是False,比如:空字符串、空列表、空元祖等
另外还有一个特殊的类型:None
>>> bool('abc')
True
>>> bool('')
False
>>> bool([1,2])
True
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
>>> bool({1,2})
True
>>> bool(None)
False
String(字符串)
Python中的字符串必须用用单引号 ' 或双引号 " 括起来
>>> type(1)
<class 'int'>
>>> type('1')
<class 'str'>
>>> type("1")
<class 'str'>
使用单双引号表示字符串是为了如下遇到缩写的情况:
>>> 'let's go'
SyntaxError: invalid syntax
>>> "let's go" #推荐,更为简洁
"let's go"
>>> 'let\'s go' #另外也可以使用转义符
"let's go"
多行字符串的表示,三个单引号
>>> '''
hello
hello
hello
'''
'\nhello\nhello\nhello\n'
>>> """
hello
hello
"""
'\nhello\nhello\n'
>>> 'hello\ #另一种方法
world'
'helloworld'
如上,\n表示特殊字符换行符,即就是在IDLE中键盘输入enter之后,会转义为 \n 来表示回车键,那么反过来,字符串中输入 \n,并不会让字符串中有 \n, IDLE 只会将 \n 当做字符,使用 print 函数会实现这种功能
>>> """hello\nhello"""
'hello\nhello'
>>> print("""hello\nhello""")
hello
hello
>>> print('hello\nhello') #单引号也有这种特性
hello
hello
转义字符:特殊的字符,一种是无法“”看见”的字符(换行符等);另一种与yu语言本身有冲突的字符
\n 换行
\' 单引号
\t 横向制表符
print 函数中,转义字符的使用
字符串前面添加 r 表示不是一个普通字符串,而是一个原始字符串,即就是其中的 \ 就是 \ 而并不是转义的作用
>>> print('hello \nworld')
hello
world
>>> print('hello \\nworld')
hello \nworld
>>> print('c:\north\north') #文件的路径中必须转义
c:
orth
orth
>>> print('c:\\north\\north')
c:\north\north
>>> print(r'c:\north\north')
c:\north\north
>>> print(r'let's go') #此处不可用 r 来解决,单引号必须是成对出现的
SyntaxError: invalid syntax
>>> r'C:\Windows'
'C:\\Windows'
>>> R'C:\Windows' #r 和 R 均可
'C:\\Windows'
字符串的简单操作
加法拼接、乘法重复
>>> "hello" + "wprld"
'hellowprld'
>>> "hello" + "world"
'helloworld'
>>> "hello" * 3
'hellohellohello'
访问字符串中任意字符:下标访问即可(0开始)
>>> "hello"[0]
'h'
>>> "hello"[3]
'l'
>>> "hello"[-1] #从末尾往前1位
'o'
字符串截取
>>> "hello world"[0:5] #从0到4
'hello'
>>> "hello world"[0:-1]
'hello worl'
>>> "hello world"[6:11]
'world'
>>> "hello world"[6:20] #大于字符串长度时,取到最后一位
'world'
>>> "hello world"[6:0] #返回空
''
>>> "hello world"[6:-0]
''
>>> "hello world"[6:] #后面没有数字,默认到最后一位
'world'
注意:
- Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始
- Python中的字符串不能改变
List(列表)
列表的定义:列表中可以添加不同的数据类型,列表中可以嵌套列表,称为嵌套列表(类似于二维数组)
>>> type([1,2,3])
<class 'list'>
>>> type(["hello", 1,2,"world", True, False, [1,2]])
<class 'list'>
列表的访问,列表的截取和字符串类似
>>> ["hello", "world", 1,2][1]
'world'
>>> ["hello", "world", 1,2][2]
1
>>> ["hello", "world", 1,2][0:2]
['hello', 'world']
>>> ["hello", "world", 1,2][-1:]
[2]
>>> type(["hello", "world", 1,2][-1:]) #用冒号取出一段字符串后,依旧是列表
<class 'list'>
列表加法、乘法
>>> ["hello", "world"] + [1,2]
['hello', 'world', 1, 2]
>>> [1,2] * 3
[1, 2, 1, 2, 1, 2]
更新列表
>>> list = ["hello", 1, 2]
>>> list[1] = 100
>>> list
['hello', 100, 2]
删除列表元素 del
>>> list
['hello', 100, 2]
>>> del list[1]
>>> list
['hello', 2]
列表的脚本操作符 in 和 for 循环
>>> 2 in [1,2,3]
True
>>> for x in [1,2,3]:
print(x)
1
2
3
Python中列表的函数:
列表的方法:
- list.append(obj)
在列表末尾添加新的对象 - list.count(obj)
统计某个元素在列表中出现的次数 - list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) - list.index(obj)
从列表中找出某个值第一个匹配项的索引位置 - list.insert(index, obj)
将对象插入列表
Tuple(元祖)
元祖的定义、访问、运算
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
>>> type((1,2,3))
<class 'tuple'>
>>> (1,2,3)[0]
1
>>> (1,2,3)[0:2]
(1, 2)
>>> (1,2,3)+(4,5,6)
(1, 2, 3, 4, 5, 6)
>>> (1,2,3)*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
但是在定义只有一个元素的tuple时,如果采用如下前两种方法,IDLE 就会默认括号为运算符当中的括号,因此定义只有一个元素的tuple必须在这个元素之后加上逗号
>>> type(('hello'))
<class 'str'>
>>> type((1))
<class 'int'>
>>> type((1,))
<class 'tuple'>
>>> type(('hello',))
<class 'tuple'>
元祖内置函数 tuple(list):将列表转换为元祖
>>> li = [1,2,3,'hello']
>>> tuple(li)
(1, 2, 3, 'hello')
到目前为止,我们学习的数据类型有:int float str list tuple,可以发现 str list tuple 三种数据类型的操作非常相似,这三种数据成为 序列
对于序列(有顺序、每个元素有序号)而言有一些通用的操作:下标访问、切片、加法、乘法、in、len() 、max() min() (字符类型时取得ASCII值最大、最小的字符)
>>> max('abcd')
'd'
>>> min('abcd')
'a'
>>> ord('a') #获取字符的ASCII值
97
集合 set
集合是无序的,不同于之前学习的三种序列,比如集合不支持下标索引访问、切片
集合是不重复的
>>> type({1,2,3}) #定义
<class 'set'>
>>> {1,1,2,2,3,3}
{1, 2, 3}
集合的一般操作:len() 函数、in
>>> len({1,2,3})
3
>>> 1 in {1,2,3}
True
>>> 1 not in {1,2,3}
False
集合的特殊用法在于:减法(可以求得两个集合的差集),& (求交集), | (求并集)
>>> {1,2,3,4} - {3,4}
{1, 2}
>>> {1,2,3,4} & {3,4}
{3, 4}
>>> {1,2,3,4} | {3,4,7}
{1, 2, 3, 4, 7}
>>> {1,2,3,4} + {3,4,7} #注意集合的加法是不存在的
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
{1,2,3,4} + {3,4,7}
TypeError: unsupported operand type(s) for +: 'set' and 'set'
定义一个空的集合
>>> type(set())
<class 'set'>
>>> len(set())
0
>>> type({}) #{}表示一个空的字典,要注意区分
<class 'dict'>
集合的基本操作:添加、移除
>>> s = {1,2,3}
>>> s.add(4) #添加
>>> s.add('hello')
>>> s
{1, 2, 3, 4, 'hello'}
>>> s.remove(2) #移除
>>> s
{1, 3, 4, 'hello'}
字典 Dict
key -> value, 属于集合类型(set),不是序列
键必须是唯一的,但值则不必。
定义、访问(只能通过 key 来访问,不能通过下标索引访问)、字典规定 key 不可以重复(创建时如果同一个键被赋值两次,后一个值会被记住)
>>> type({1:'hello', 2:'world'})
<class 'dict'>
>>> {1:'hello', 2:'world'}[1]
'hello'
>>> {1:'hello', 2:'world', 2:'www'}
{1: 'hello', 2: 'www'}
对于字典的 key 值的选取,可以是 int 或者 字符,1 与 '1' 视为不同的 key
>>> {1:'hello', '1':'world'}
{1: 'hello', '1': 'world'}
>>> {1:'hello', '1':'world'}[1]
'hello'
>>> {1:'hello', '1':'world'}['1']
'world'
字典中的value值可以取任意类型,包括但不限于我们之前学习的 str int float list set dict
但是 key 的取值必须是不可变的类型, 比如:int str tuple 而不能是 List
字典的修改
>>> dict = {'name':'julia', 'age':'20'}
>>> dict
{'name': 'julia', 'age': '20'}
>>> dict['age'] = 16
>>> dict
{'name': 'julia', 'age': 16}
字典的删除
>>> del dict['age'] #删除键
>>> dict
{'name': 'julia'}
>>> del dict #删除字典