Python中的基本数据类型有:整型(int)、浮点型(float)、布尔(bool)、复数(complex)字符串(str)、列表(list)、元组(tuple)、集合(set)、字典(dict)等。
Number:
二进制用:0b | bin:可以把其他进制的转为二进制 |
八进制用:0o | int:可以把其他进制的转为十进制 |
十六进制:0x | hex:可以把其他进制的转为十六进制 |
oct:可以把其他进制的转为八进制 |
用type()可以查看类型:
值得注意的是:
>>> type(2/2)
<class 'float'>
>>> type(2//2)<class 'int'>
1/2=0.5 而 1//2=0;2/2=1.0 2//2=1
一般用于比较和判断,一个布尔值只有True、False两种值。在比较、逻辑、成员、身份运算中,返回结果都为布尔值。
str字符串:
用单引号、双引号表示字符串。
转义字符:\n:换行;\':单引号;\t:制表符;\r:回车
字符串的运算:>>> 'hello'+'hello'
'hellohello'
>>> 'hello'*2
'hellohello'
>>> 'hello world'[0]
'h'
>>> 'hello world'[-1]
'd'
>>> 'hello world'[0:4]#下一位
'hell'
>>> 'hello world'[0:5]
'hello'
>>> 'hello world'[6:-1] #这样并不能得到world
'worl'
>>> 'hello world'[6:]
'world'
>>> 'hello world'[:] #返回所有元素
'hello world'
list 列表:
用[]表示,中间元素之间用逗号隔开,元素的类型可以不同,可以重复,是有序的,可以用下标索引来访问,可以切片操作。字符串,列表,元组都是有序的。
定义一个空列表:a=[]
嵌套列表:list=[[1,2],['hello',1,2],[True,False],3]
列表的运算和字符串一样,元组也一样
列表中元素的提取和字符串一样,值得注意的是:用单一数字的方式来访问列表得到字符串,而用冒号的方式则是会得到一个列表,哪怕这个列表只有一个元素。
>>> [1,2,3][2:]
[3]
>>> list_x=[[1,2],['hello',1,2],[True,False],3]
>>> list_x[1][2]
2
>>> list_x[1][2]='4'
>>> print(list_x)
[[1, 2], ['hello', 1, '4'], [True, False], 3]
>>> list_x.append(6)
>>> print(list_x)
[[1, 2], ['hello', 1, '4'], [True, False], 3, 6]
list_x=[[1, 2], ['hello', 1, '4'], [True, False], 3, 6, 6]
>>> list_x.reverse() #倒转
>>> list_x
[6, 6, 3, [True, False], ['hello', 1, '4'], [1, 2]]
>>> list_x.count(6) #计算对象6出现的次数
2
>>> len(list_x) #返回长度
6
tuple元组:
元组和列表相似,不同之处在于,元组用()表示,列表用[],而且元组内的元素是不能修改。
定义一个空元组的方法是:a=(),只有一个元素的元组是:a=(7,)
判断是否在元组中用in
>>> 3 in (1,2,3)
True
>>> 3 not in (1,2,3)
False
列表和字符串也也一样
>>> 'h' in 'hello'
True
set集合:
集合用{}表示,它的特性是:无序的,不重复
定义一个空集合:a=set()
>>> {1,2,3,4,5,6}-{4,5} #差集/减去相同的
{1, 2, 3, 6}
>>> {1,2,3,4,5,6}&{4,5} #交集/共有元素
{4, 5}
>>> {1,2,3,4,5,6}|{4,5,7} #合集、并集
{1, 2, 3, 4, 5, 6, 7}
dict字典:
{key1:value1,key2:value2...}
字典也是无序的,定义一个空的字典是a={}
字典是通过key来访问value的,字典中不能有相同的key
>>> a={2:'hello','2':3}
>>> a[2]
'hello'
>>> a['2']
3
value:可以是str/int/float/list/set/dict
key:必须是不可变的类型(int/str)不能用list但是可以用tuple