Python的基本数据类型

基本数据类型介绍~

Number:数字

整数(int)

1
2
3
4
5
>>> 1
1

>>> type(1)
<class 'int'>

浮点数(float)

1
2
3
4
5
>>> 1.5
1.5

>>> type(1.5)
<class 'float'>

布尔类型(bool)

非空,非0大部分都为true

1
2
3
4
5
6
bool(-1)  //true
bool(1) //true
bool('aa') //true
bool(0) //false
bool('') //false
bool(None) //false

复数(complex)

1
36j

进制转换问题

1
2
3
4
5
6
7
8
9
10
11
12
13
Ob10  //2进制
0o10 //8进制
0x10 //16进制
0x1F //16进制 31

>>> bin(10) //(任何进制)转2进制
'0b1010'
>>> oct(0b111) //(任何进制)转8进制
'0o7'
>>> int(0b111) //(任何进制)转10进制
7
>>> hex(0o77) //(任何进制)转16进制
'0x3f'

序列

字符串(str)
引号

单引号 : 包裹则为字符串

双引号:内部可以包裹单引号

三引号:可以换行(79建议换行)

1
2
3
4
5
6
7
8
>>>"let's go"
"let's go"

>>> """
hello world
liupeng
"""
'\nhello world\nliupeng\n'
转义字符

\n 换行

\‘ 单引号

\t 横向制表符

\r 回车

1
2
3
4
5
6
7
8
>>>'let\'s go'

>>>print('hello \n world')
'hello
world'

>>>print(r'c:\nhello\nworld') //原始字符串
'c:\nhello\nworld'
字符串的计算

按步长进行计算,尾部截取需要大一位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>>"hello " + "world"
'hello world'

>>>"hello"*3
'hellohellohello'

>>>"hello world"[0]
'h'

>>>"hello world"[-1]
'd'

>>>"hello world"[0:5]
'hello'
列表(list)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> [1,2,3,4]
[1, 2, 3, 4]

>>> type([1,2,3,4])
<class 'list'>

>>> type([1,2,3,4,True,False,'world'])
<class 'list'>

>>> type([1,2,3,[5,1],True,False,'world'])
<class 'list'>

>>> [1,2,3,4][0]
1

>>> [1,2,3,4][0:2]
[1, 2]

>>> [1,2,3,4]*3
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

>>> [1,2,3,4]+[7,8]
[1, 2, 3, 4, 7, 8]
元组(tuple)

数据操作和list没区别(不过引用不可变)

1
2
3
4
5
6
7
8
9
10
11
>>> (1,2,3,4,5)
(1, 2, 3, 4, 5)

>>> type((1,2,4,5))
<class 'tuple'>

>>> type((1))
<class 'int'>

>>> type(())
<class 'tuple'>
常用函数

序列的都可以用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 3 in [1,2,3,4,5]
True

>>> 3 not in [1,2,3,4,5]
False

>>> len([1,2,3,4,5])
5

>>> max([1,2,3,4,5])
5

>>> min([1,2,3,4,5])
1

>>> ord('a')
97
>>> ord(' ')
32

集合(set)

无序,不可重复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> {1,2,3}
{1, 2, 3}

>>> type({1,2,3,4})
<class 'set'>

>>> {1,2,1,5,2}
{1, 2, 5}

>>> 1 in {1,2,3,4}
True

>>> 1 not in {1,2,3,4}
False

>>> {1,2,3,4} - {1,2}
{3, 4}

>>> {1,2,3,4} & {1,2}
{1, 2}

>>> {1,2,3,4} | {1,2,8}
{1, 2, 3, 4, 8}

>>> type(set())
<class 'set'>

字典(dict)

key - value (key不可以重复,引用不可改变)

1
2
3
4
5
6
7
8
9
10
11
>>> {1:1,2:2}
{1: 1, 2: 2}

>>> type({1:1,2:2})
<class 'dict'>

>>> {'q':1,'w':2}['q']
1

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

总结