第四章 操作列表(遍歷列表)
遍歷列表:
nums = ['1','2','3','4']
for num in nums:
print(num)
>for後面,沒有縮排的程式碼,只執行一次,不會重複執行。
會顯示錯誤:IndentationError: expected an indented block
修改為:
nums = ['1','2','3','4']
for num in nums: >for迴圈,從nums列表中逐次取出一個元素放入num中並輸出,直至nums列表中無元素存在
print(num) >此行縮排才可
>>>1 2 3 4
建立數值列表:
range()函式
for value in range(1,5):
print(value) >>>1 2 3 4 不包含5
使用list()可將range()的結果直接轉換成列表
nums = list(range(1,6))
print(nums) >>>[1,2,3,4,5]
nums = list(range(2,11,2))
print(nums) >>>取2到11之間的偶數,不斷加2
square.py >輸出前10個整數的平方加入一個列表中
squares = []
for value in range(1,11): 不要丟掉冒號(:)
square = value**2
squares.append(square)
print(squares)
對數字列表進行簡單的統計運算(求最大值、最小值、求和)
digits = [1,2,3,4]
min(digits)
digits = [1,2,3,4]
max(digits)
digits = [1,2,3,4]
sum(digits)
列表解析:
squares = [value**2 for value in range(1,11)]
print(squares)
切片:
bicycles[0:3] bicycles[0:] bicycles[:3] bicycles[:]
遍歷切片:
for car in cars[:]:
print(car)
複製列表:
a_cars = cars[:] >不能寫成 a_cars = cars
元組: >不可變的列表,使用圓括號而不是方括號
dimensions = (200,50)
遍歷元組中的所有值(方法類似列表的操作)
元組的元素不能修改,但是可以給元組的變數賦值
dimensions = (200,50)
dimensions = (400,100)
程式碼格式相關:
1,易於閱讀
2,每級縮排使用四個空格,提升可讀性。(避免使用製表符和空格混用)
3,行長:每行不超過80字元,註釋不超過72字元
課後題:
# 4-1 遍歷列表 pizzas = ['a','b','c'] for pizza in pizzas: print("I Like " + pizza + "!") print("I Really Love Pizza!") # 4-2 動物 pets = ['cat','dog','pig'] for pet in pets: print("A"+ pet +"would make a great pet") print("Any of these animals would make a great pet !") # 4-3 列印數字 1-20 for i in range(1,21): print(i) # 4-4 練習Ctrl +C 來停止執行 # 4-5 計算1-100001的總和 a = [] for i in range(1,100001): a.append(i) print(min(a)) print(max(a)) print(sum(a)) # 4-6 列印 1-20的奇數 for i in range(1,21,2): print(i) # 4-7 列印3的倍數 for i in range(3,31,3): print(i) # 4-8 列印1-10整數的立方 nums = [] for i in range(1,11): nums.append(i**3) print(nums) for num in nums: print(num) # 4-9 將上面的列表,進行解析 nums = [i**3 for i in range(1,11)] for num in nums: print(num) # 4-10 列表切片 nums = [i**3 for i in range(1,11)] print(nums) print("The first three items in the list are : " + str(nums[0:3])) print("Three items from the middle of the list are : " + str(nums[3:6])) print("The three items in the last are : " + str(nums[7:11])) # 4-11 pizzas = ['a','b','c'] friend_pizzas = ['a','b','c'] friend_pizzas.append('d') print(friend_pizzas) pizzas.insert(3,'f') print(pizzas) print("My favorite pizzas are: ") for pizza in pizzas: print(pizza) print("My friend's favorite pizzas are: ") for friend_pizza in friend_pizzas: print(friend_pizza) # 4-12 元組初步 foods = ('a','b','c','d','f') for food in foods: print(food) # foods[0] = tf print(foods) foods = ('a','b','c','j','k') for food in foods: print(food)