Python3入门到精通--基本数据类型

作者: Daniel Meng

GitHub: LibertyDream

博客:明月轩

本系列教程采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议

asd

Number:数字

数字类型可分为数值类和布尔类型。数值类又分为整型和浮点型两种。

python3中取消了short,long类型,统一用int表示整数。取消了double类型,统一用float表示,这里的float就是其他语言中的双精度double

使用方法type(a),可以获知参数a的类型

In [2]:
type(-1)
Out[2]:
int
In [3]:
type(1.1)
Out[3]:
float
In [4]:
type(1 * 1)
Out[4]:
int
In [5]:
type(1 + 0.1)
Out[5]:
float

python3中默认/为浮点除法,用//表示整除

In [6]:
type(2 // 2)
Out[6]:
int

进制与进制转换

生活中常用的进制是10进制,计算机中常用的是2、8、16进制。

python3中默认进制为10进制。想要显示的表示2进制可以使用0bxxx这样的方式,如0b11表示10进制的3。同理,8进制和16进制可以使用0oxxx0xaaa的方式表示,如0o10,0x1F,分别表示10进制的8和31

存在进制就有进制转换的问题。python3中提供了下列方法进行进制转换:

  • int(a)将某进制数a转换成10进制数
  • bin(a)将某进制数a转换成2进制数
  • oct(a)将某进制数a转换成8进制数
  • hex(a)将某进制数a转换成16进制数
In [8]:
hex_num = 0b111111 # 初始化一个二进制数
In [9]:
int(hex_num)
Out[9]:
63
In [10]:
bin(hex_num)
Out[10]:
'0b111111'
In [11]:
oct(hex_num)
Out[11]:
'0o77'
In [12]:
hex(hex_num)
Out[12]:
'0x3f'

布尔类型与复数

布尔类型:bool,负数complex。

bool(a)方法可以将a转化为真假值TrueFalse注意大小写

布尔类型属于Number是因为真假值是可以向数值转换的

In [13]:
int(True)
Out[13]:
1
In [27]:
int(False)
Out[27]:
0

所有非0值都为True

In [15]:
bool(1)
Out[15]:
True
In [16]:
bool(0)
Out[16]:
False
In [17]:
bool(2)
Out[17]:
True
In [18]:
bool(-1)
Out[18]:
True
In [19]:
bool(0)
Out[19]:
False

所有非空值皆为True

In [20]:
bool('abc') # 非空字符串
Out[20]:
True
In [21]:
bool('') # 空字符串
Out[21]:
False
In [22]:
bool([]) # 空列表
Out[22]:
False
In [23]:
bool({}) # 空字典
Out[23]:
False
In [28]:
bool({1,2,3}) # 非空集合
Out[28]:
True

Python中有一个专门表示“空”这一概念的值——None

In [25]:
bool(None)
Out[25]:
False

复数表示方法很简单,在数值后加上标识符j即可。如36j

In [26]:
type(36j)
Out[26]:
complex

str:字符串

字符串是使用单引号`,双引号" ",和三引号"""/''' '''包括的内容。

In [29]:
'hello world'
Out[29]:
'hello world'
In [30]:
1
Out[30]:
1
In [31]:
'1'
Out[31]:
'1'
In [32]:
type(1)
Out[32]:
int
In [33]:
type('1')
Out[33]:
str
In [34]:
"hello"
Out[34]:
'hello'
In [35]:
type("hello")
Out[35]:
str

用于表示字符串类型的引号必须成对出现,而在表征字符串的引号中插入其他类型的引号不会有问题,即便不成对。如果是同类型的引号可以使用\进行转义。

In [37]:
'let's go'
  File "<ipython-input-37-58d8c8a129df>", line 1
    'let's go'
         ^
SyntaxError: invalid syntax
In [38]:
'let"s go'
Out[38]:
'let"s go'
In [39]:
'let\'s go'
Out[39]:
"let's go"

python建议每行字符数不超过80,当字符串内容超长,可以使用三引号来表示

In [40]:
'''
hello world
hello world
'''
Out[40]:
'\nhello world\nhello world\n'
In [41]:
"""
hello world
hello world
hello world
"""
Out[41]:
'\nhello world\nhello world\nhello world\n'

不仅可见的abc这样的字符会被录入,回车符虽不可见带也会被录入,最后表现为\n的形式。

如果想在一行字符串中自定换行,可以使用print()搭配转义字符\n

In [42]:
""" hello world \n hello world\nhello world\n"""
Out[42]:
' hello world \n hello world\nhello world\n'
In [44]:
print("""hello world \nhello world\nhello world\n""")
hello world 
hello world
hello world

In [45]:
print('hello world \n hello world\nhello world\n')
hello world 
 hello world
hello world

单引号和双引号内内容的换行,可以选择字符串行尾加上\

In [46]:
"""hello world
hello world"""
Out[46]:
'hello world\nhello world'
In [48]:
'hello\
 world'
Out[48]:
'hello world'

转义字符

在输入文字中有下列情况需要特殊处理:

  • 特殊字符
  • “看不见的字符”,换行、制表符等
  • 与语言标准相冲突的字符,比如python中的'

所以有了转义字符,形式为\+字母,比如说\r回车,\n换行,\t横向制表符,或者是\'为了输出'

\r\n的区别

\r——移动光标至行首

\n——光标下移一格

不同系统对于换行采取的方式不同

  • Unix系统,行尾是\n
  • Windows系统,每行结尾是\n\r
  • Mac系统里,每行结尾是\r

Python能根据系统自动判别换行符的形式。但对如下输入,不同系统结果是一致的:

print aaaa \r bbbb
print aaaa \n bbbb

输出

 bbbb
aaaa
 bbbb
In [52]:
print('aaaa \r bbbb')
print('aaaa \n bbbb')
 bbbb
aaaa 
 bbbb

原始字符串

当想要将\n本身作为字符串内容输出时,有两种方式,一是对\进行转义操作,即\\,另一种是在字符串前加上标志符r

In [53]:
print('c:\north\northwest')
c:
orth
orthwest
In [54]:
print('c:\\north\\northwest')
c:\north\northwest

注意,转换字符串为原始字符串的前提是字符串本身合法

In [55]:
 r'let"s go'
Out[55]:
'let"s go'
In [56]:
r'let's go'
  File "<ipython-input-56-c780336dbdc2>", line 1
    r'let's go'
          ^
SyntaxError: invalid syntax

字符串的运算

字符串同数字一样,存在一些基本的四则运算操作,+用来拼接字符串,*用来复制字符串,必须是一个字符串和一个数做乘积

In [57]:
"hello"+" world"
Out[57]:
'hello world'
In [58]:
"hello "*3
Out[58]:
'hello hello hello '
In [59]:
"hello"*"world"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-fd5f00c65ffd> in <module>()
----> 1 "hello"*"world"

TypeError: can't multiply sequence by non-int of type 'str'

为了获取字符串中特定位置的元素,可以在字符串后加上[num],表明希望取到num位置的元素。

num为正时,从左往右,从0开始计数。为负时,从右往左,从-1开始计数

In [60]:
 "hello world"[0]
Out[60]:
'h'
In [61]:
"hello world"[4]
Out[61]:
'o'
In [62]:
"hello world"[-1]
Out[62]:
'd'
In [63]:
"hello world"[-3]
Out[63]:
'r'

为了获取字符串中的一段,使用[start:end]的方式获取[start,end)范围内的字符串内容,start小于end时为空

In [64]:
"hello world"[0:4]
Out[64]:
'hell'
In [65]:
"hello world"[0:5]
Out[65]:
'hello'
In [66]:
"hello world"[0:-1]
Out[66]:
'hello worl'
In [70]:
"hello world"[-2:2]
Out[70]:
''

为了取到全部的字符串,特别是末尾的元素,可以令end>=str.length,当不写startend时,默认为从头开始取,和一直取到尾

In [71]:
"hello world"[6:11] # 空格也是一个字符
Out[71]:
'world'
In [72]:
"hello world"[6:20]
Out[72]:
'world'
In [73]:
"hello world"[6:]
Out[73]:
'world'
In [74]:
"hello world"[:-4]
Out[74]:
'hello w'
In [75]:
"hello world"[-5:]
Out[75]:
'world'

英雄技能qwer是一组,世界杯小组赛会分组。基本数据类型都源自于生活中的抽象。 python中有多个表示“组”概念的类型,专业名词叫做 序列 。顾名思义,其含义是类型对象中的每个元素都有一个能标识自身的 序号 。序列下面有列表和元组两个。

列表:list

列表表示方式为[xxx],内置元素类型不用刻意一致,可以类型混合,当然也可以嵌套

In [76]:
type([1,2,3,4,5,6])
Out[76]:
list
In [77]:
type(["hello","world",1,9])
Out[77]:
list
In [78]:
type(["hello","world",1,9,True,False])
Out[78]:
list
In [79]:
type([[1,2],[True,False]])
Out[79]:
list

列表的基本操作常用的有取值,截取(切片),列表拼接(加法),列表复制(乘法)

In [80]:
["新月打击","苍白之暴","月神冲刺","月之降临"][0]
Out[80]:
'新月打击'
In [81]:
["新月打击","苍白之暴","月神冲刺","月之降临"][3]
Out[81]:
'月之降临'
In [82]:
["新月打击","苍白之暴","月神冲刺","月之降临"][0:2]
Out[82]:
['新月打击', '苍白之暴']
In [83]:
["新月打击","苍白之暴","月神冲刺","月之降临"][-1:]
Out[83]:
['月之降临']
In [84]:
["新月打击","苍白之暴","月神冲刺","月之降临"]+['点燃','虚弱']
Out[84]:
['新月打击', '苍白之暴', '月神冲刺', '月之降临', '点燃', '虚弱']
In [85]:
['点燃','虚弱']*['点燃','虚弱'] # 必须是 list * 数字
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-8fe6ce87dc47> in <module>()
----> 1 ['点燃','虚弱']*['点燃','虚弱']

TypeError: can't multiply sequence by non-int of type 'list'
In [86]:
['点燃','虚弱']*3
Out[86]:
['点燃', '虚弱', '点燃', '虚弱', '点燃', '虚弱']

留心列表无减法操作(字符串同理)

In [87]:
 ['点燃','虚弱']-['点燃']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-73a42fce2f75> in <module>()
----> 1 ['点燃','虚弱']-['点燃']

TypeError: unsupported operand type(s) for -: 'list' and 'list'
In [88]:
'aaa' - 'a'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-88-ca4bd424d909> in <module>()
----> 1 'aaa' - 'a'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

元组: tuple

元组是另一个表示“组”概念的数据类型。使用(xxx)表示。和列表一样,数据类型可以不一致。基本操作也是基本一致的。

In [89]:
(1,2,3,4,5)
Out[89]:
(1, 2, 3, 4, 5)
In [95]:
type((1,2,3,4,5))
Out[95]:
tuple
In [90]:
(1,'-1',True)
Out[90]:
(1, '-1', True)
In [91]:
(1,2,3)[0]
Out[91]:
1
In [92]:
(1,2,3,4)[0:2]
Out[92]:
(1, 2)
In [93]:
(1,2,3)+(4,5,6)
Out[93]:
(1, 2, 3, 4, 5, 6)
In [94]:
(1,2,3)*3
Out[94]:
(1, 2, 3, 1, 2, 3, 1, 2, 3)

()本身即是元组标识,也是数学运算符。

In [96]:
(1)*2
Out[96]:
2
In [97]:
(1)
Out[97]:
1
In [98]:
type((1))
Out[98]:
int
In [99]:
type(('string'))
Out[99]:
str

为了避免歧义,python默认当括号内只有一个元素时,()作数学运算符处理。为了表示只有一个元素的元组,可以参考下法,列表等则无此问题

In [100]:
(1,)
Out[100]:
(1,)
In [101]:
type((1,))
Out[101]:
tuple
In [102]:
type([1])
Out[102]:
list

空元组表示方式很简单,单纯的()即可

In [103]:
type(()) # 空元组
Out[103]:
tuple

序列共性

  • []取值
In [108]:
'hello world'[2]
Out[108]:
'l'
In [106]:
[1,2,3][2]
Out[106]:
3
In [107]:
[1,2,3,4,5][0:3]
Out[107]:
[1, 2, 3]
In [109]:
"hello world"[0:8:2]
Out[109]:
'hlow'

[0:8:2],最后一个参数表示 步长

  • 存在性判断
In [110]:
3 in [1,2,3,4,5,6]
Out[110]:
True
In [111]:
2 not in [1,2,3,4,5,6]
Out[111]:
False
  • 长度
In [112]:
len([1,2,34,5])
Out[112]:
4
In [113]:
len('hello world')
Out[113]:
11
  • 最值
In [114]:
max([1,2,3,4,5,6])
Out[114]:
6
In [115]:
min('abcde')
Out[115]:
'a'

字符可以比大小是因为所有字符都是经过编码的,即每一个字符都有一个特定的值对应,我们叫做 ascll码 ,使用ord()可以获取参数的ascll码

In [116]:
ord('a')
Out[116]:
97
In [117]:
ord(' ') # 空格符也有ascll码
Out[117]:
32

集合

说完序列的有序,该说无序的了,即set,集合。用{}表示。因为无序所以不能获取指定序号的元素,也就无从谈起切片(截取内容)了

In [118]:
type({1,2,3,4,5,6})
Out[118]:
set
In [119]:
{1,2,3,4,5,6}[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-119-0eba15296f2c> in <module>()
----> 1 {1,2,3,4,5,6}[0]

TypeError: 'set' object does not support indexing
In [120]:
{1,2,3,4,5,6}[0:1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-120-37e3b05473dd> in <module>()
----> 1 {1,2,3,4,5,6}[0:1]

TypeError: 'set' object is not subscriptable

集合可以存放不同类型数据,但必须是能哈希化的数据(即数值不变性),列表不能哈希化

In [121]:
{1,2,'3',[1,2,3]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-121-70887522d801> in <module>()
----> 1 {1,2,'3',[1,2,3]}

TypeError: unhashable type: 'list'
In [122]:
{1,2,'3',(1,2,3)}
Out[122]:
{(1, 2, 3), 1, 2, '3'}

python的集合元素也有特异性,无序性的特点

In [123]:
{1,1,2,3,3,4}
Out[123]:
{1, 2, 3, 4}
In [124]:
{1,3,4,2,7}
Out[124]:
{1, 2, 3, 4, 7}

集合支持和序列一样的存在性判断和长度获取操作。

In [125]:
len({1,2,3})
Out[125]:
3
In [126]:
1 in {1,2,3}
Out[126]:
True
In [127]:
4 not in {4,5,6}
Out[127]:
False

集合最重要的是三个逻辑判断,差、交、并

In [128]:
{1,2,3,4,5,6} - {1,3,5}
Out[128]:
{2, 4, 6}
In [129]:
{1,2,3,4,5,6} & {1,3,5}
Out[129]:
{1, 3, 5}
In [130]:
{1,2,3,4,5,6} | {3,5,7}
Out[130]:
{1, 2, 3, 4, 5, 6, 7}

表示空集有些特殊,因为{}表示的是另一个数据类型——字典的空值

In [131]:
type(set())
Out[131]:
set
In [132]:
len(set())
Out[132]:
0

字典:dict

字典类型是一种特殊的集合,采用键-值对形式构建。创建方式为{key:value,key:value,....}。是集合当然不能角标访问,正确的方式是{k1:v1,...}[key],得到对应value

In [133]:
type({1:1,2:2,3:3})
Out[133]:
dict
In [134]:
{'Q':'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}[0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-134-bd319ab62fc6> in <module>()
----> 1 {'Q':'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}[0]

KeyError: 0
In [135]:
{'Q':'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}['Q']
Out[135]:
'新月打击'
In [136]:
{'Q':'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}['R']
Out[136]:
'月神冲刺'

虽然不会报错,但务必保证key唯一,否则丢数据算轻的

In [137]:
{'Q':'新月打击','Q':'苍白之瀑','E':'月之降临','R':'月神冲刺'}['Q']
Out[137]:
'苍白之瀑'
In [138]:
{'Q':'新月打击','Q':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
Out[138]:
{'E': '月之降临', 'Q': '苍白之瀑', 'R': '月神冲刺'}

key必须是不可变类型(能哈希化),比如str、int、元组。value可以是任意类型,甚至可以嵌套字典

In [139]:
{1:'新月打击','1':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
Out[139]:
{1: '新月打击', '1': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}
In [140]:
type({'Q':'新月打击','W':'苍白之瀑','E':{1:1},'R':'月神冲刺'})
Out[140]:
dict
In [141]:
{[1,2]:'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-141-cb026c09b0f1> in <module>()
----> 1 {[1,2]:'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}

TypeError: unhashable type: 'list'
In [142]:
 {(1,2):'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
Out[142]:
{(1, 2): '新月打击', 'E': '月之降临', 'R': '月神冲刺', 'W': '苍白之瀑'}