快速過一遍Python中常用的資料型別和程式結構以及基本語法,主要有串列,字典,for回圈語法,if-else陳述句等基本知識,
1. 串列
串列是有序集合,可以修改,用中括號[ ]修飾,下標從0開始,形如colors = ['red','blue','black','green']
| 訪問和修改元素 | colors[index] |
| 末尾添加元素 | colors.append() |
| 插入元素 | colors.insert(index, content) |
| 洗掉元素 | del colors[index] 等同于colors.pop(index) 區別于colors.pop()洗掉后能夠接著使用 |
| 根據值洗掉元素 | colors.remove(content) |
| 排序 | colors.sort() |
| 翻轉 | colors.reverse() |
| 確定長度 | len(colors) |
| 切片 | colors[0:2]指的是'mouse','display' |
| 遍歷切片 | 也是for回圈 for color in colors[0:3] |
| 復制串列 | new = colors[:] 不加任何索引 |
| 元組:不可變的串列,用圓括號( )修飾 | 形如values = (10,20,30) values[0] = 40(ERROR) values = (20,30,40)(Right)可以重新賦值,但不能夠修改 |
2. 字典
字典就是鍵-值對,用{ }來修飾,形如student = {'name':'zs','score':'90','age':'25'}
| 訪問字典中的value | print(student['score']) |
| 修改字典中的值 | student['score'] = '80' |
| 添加鍵-值對 | student['height'] = '175' |
| 洗掉鍵-值對 | del['age'] |
| 遍歷所有的鍵值對 | for key,value in student.item(): |
| 遍歷所有的鍵 | for key in student.keys(): |
| 遍歷所有的值 | for key in student.values(): |
| 字典串列 | 本質上是串列,存盤的元素為字典 這里和指標陣列和陣列指標很像 |
| 在字典中存盤串列 | 本質上是字典 |
3. 程式結構
| for回圈 for cat in cats: python中通過縮進,C語言中要用{ },不要遺漏冒號 | |
| if 條件: 陳述句1 else: 陳述句2 | 多個條件時,用and 或者or 連接 |
| range(1,10,2)函式 | 左閉右開,1~9,步長為2 |
| digits = list(range(1,10,2)) 求最大值,最小值,求和 | 轉換成數字串列 max(),min(),sum() |
| ** | 表示平方 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/243842.html
標籤:python
上一篇:robotest介面自動化測驗之引數傳遞so easy
下一篇:用Python寫一個植物大戰僵尸
