Python中一切皆是對象,主要的內置對象有:1. 數字(整型int、浮點型float)2. 字符串(不可變性) 3.列表 4.字典 5.元組(不可變性) 6.文件 7.集合(不重復性)
數字:支持+-*/運算,有強大的math模塊
>>> round(3.1415926,2)
3.14(保留小數點位數)
>>> num = '%.2f' %3.1414596
>>> num
'3.14'(字符串格式化,輸出為字符串)
字符串:切片、索引、查找、替換、格式化,循環
>>> 'ming'[2] 索引
'n'
>>> 'ming'.index('n') 索引
2
>>> 'ming'.find('n')查找還可以用re模塊
2
>>> 'ming'.replace('n','m')替換修改字符串的一個方法
'mimg'
>>> 'I am %s and %d years old' %('ming',18)字符串的格式化
'I am ming and 18 years old'
>>> 'ming'[::-1]
'gnim' 反轉功能
列表:切片、索引、循環、追加、
>>> l.append('ming') append追加至列表
>>> l
['hello', 'world', 'python', 'ming']
>>> l.extend('lily') extend是加的列表和append有區別
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y']
>>> l.extend(['hah','hey']) 追加到一個列表
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey']
>>> l.append(['nihao','hao']) 追加啥是啥
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]
>>> l.sort() 嵌套列表不支持排序
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
l.sort()
TypeError: '<' not supported between instances of 'list' and 'str'
>>> l
['hah', 'hello', 'hey', 'i', 'l', 'l', 'lily', 'ming', 'python', 'world', 'y', ['nihao', 'hao']]
>>> l=['l','h','i']
>>> l.sort()
>>> l
['h', 'i', 'l']
>>> l.reverse() 取反
>>> l
['l', 'i', 'h']
字典:映射、嵌套、循環、排序
>>> dict = {'ming':'hangzhou','li':'nanjing','lucy':'shanghai'}
>>> dict['li'] 映射
'nanjing'
>>> dict['jim'] = 'shenzhne' 填充字典
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>> l = list(dict.keys()) 獲取字典的鍵
>>> l
['ming', 'li', 'lucy', 'jim']
>>> l.sort() 排序
>>> l
['jim', 'li', 'lucy', 'ming']
>>> for each in l: 格式化輸出
print(each,dict[each])
jim shenzhne
li nanjing
lucy shanghai
ming hangzhou
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>> value = dict.get('good','moring')字典的查找get方法,沒有則返回預設值而不報錯
>>> value
'moring'
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>>
元組:一個不可變的列表
>>> T = (1,2,3,4)
>>> T.count(1)
1
>>> T.append(5) 由於不可變性,所以不能追加
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
T.append(5)
AttributeError: 'tuple' object has no attribute 'append'
集合:不重復性 支持集合運算
>>> a = {1,3,4,5}
>>> b ={1,2,4,5,6, 7}
>>> a&b交集
{1, 4, 5}
>>> a|b並集
{1, 2, 3, 4, 5, 6, 7}
>>> a-b a中有b中沒有
{3}
>>> b-a b中有a中沒有
{2, 6, 7}
>>> a^b ab交集中沒有的
{2, 3, 6, 7}
>>>
