python的基礎04 操作列表
阿新 • • 發佈:2019-01-05
4.1 遍歷整個列表
magicians = ['alice','david','carolina'] # 定義了一個列表 for magician in magicians: # 定義了一個for迴圈 '''這行程式碼讓python從列表migicians中取出一個值,並將這個值儲存在了變數magician裡面''' print(magician) # python會打印出儲存在變數magician中的每一個值
alice
david
carolina
4.1.1 深入地研究迴圈
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
- 上面程式碼解讀
- 第一行我們定義了一個列表
- for magician in magicians:這行程式碼讓python獲取列表magicians裡的第一個值('alice'),並將其儲存到了變數magician中
- 然後,python會讀取下一行程式碼,print(magician),打印出變數magician的值
- 因為列表中還有其它的元素,所以python又返回到迴圈的這一行for magician in magicians:,python會獲取列表的第二個值('david'),並將它存放在變數magician中,在執行下面的print(magician).
- python再次執行for magician in magicians:,把第三個值放在變數magician中,打印出第三個值.
- 列表中沒有其它值了,所以這個迴圈才會結束,python才會繼續執行下面的程式碼.
4.1.2 在for迴圈中執行更多的操作
# for迴圈練習 magicians = ['alice','david','carolina'] for magician in magicians: # 在for迴圈中,想包含多少行程式碼都可以,只是後面屬於迴圈的程式碼都要使用同一個等級的縮排 print(magician + ',' + "that was a great trick!") print("I can't wait to see your next trick" + ',' + magician + '.')
alice,that was a great trick!
I can't wait to see your next trick,alice.
david,that was a great trick!
I can't wait to see your next trick,david.
carolina,that was a great trick!
I can't wait to see your next trick,carolina.
4.1.3 在for迴圈結束後執行一些操作
- 在for迴圈後面,沒有縮排的程式碼都只執行一次,不會重複執行.
magicians = ['alice','david','carolina'] for magician in magicians: print(magician + ',' + "that was a great trick!") print('I can\'t wait to see your next trick' + ',' + magician + '.\n') print("Thank you,everyone.That was a great magic show!")
alice,that was a great trick!
I can't wait to see your next trick,alice.
david,that was a great trick!
I can't wait to see your next trick,david.
carolina,that was a great trick!
I can't wait to see your next trick,carolina.
Thank you,everyone.That was a great magic show!
動手試一試
# 4-1 比薩:想出至少三種你喜歡的比薩,將其名稱儲存在一個列表中,再使用 for迴圈將每種比薩的名稱都打印出來。 pizzas = ['New York Style','Pan Pizza','Thick style'] for pizza in pizzas: print(pizza) print('\n') # 修改這個 for 迴圈,使其列印包含比薩名稱的句子,而不僅僅是比薩的名稱。對於每種比薩,都顯示一行輸出,如“ I like pepperoni pizza”。 pizzas = ['New York Style','Pan Pizza','Thick style'] for pizza in pizzas: print("I like" + ' ' + pizza) print('\n') # 在程式末尾新增一行程式碼,它不在 for 迴圈中,指出你有多喜歡比薩。輸出應包含針對每種比薩的訊息,還有一個總結性句子,如“ I really love pizza!”。 pizzas = ['New York Style','Pan Pizza','Thick style'] for pizza in pizzas: print("I like" + ' ' + pizza) print("I really love pizza!")
New York Style
Pan Pizza
Thick style
I like New York Style
I like Pan Pizza
I like Thick style
I like New York Style
I like Pan Pizza
I like Thick style
I really love pizza!
#4-2 動物:想出至少三種有共同特徵的動物,將這些動物的名稱儲存在一個列表中,再使用 for 迴圈將每種動物的名稱都打印出來。 animals = ['cat','dog','monkey'] for animal in animals: print(animal) print('\n') # 修改這個程式,使其針對每種動物都列印一個句子,如“ A dog would make a greatpet”。 animals = ['cat','dog','monkey'] for animal in animals: print("A",animal,"would make a great pet.") print("\n") # 在程式末尾新增一行程式碼,指出這些動物的共同之處,如列印諸如“ Any of theseanimals would make a great pet!”這樣的句子。 animals = ['cat','dog','monkey'] for animal in animals: print("A",animal,"would make a great pet.") print("Any of theseanimals would make a great pet!")
cat
dog
monkey
A cat would make a great pet.
A dog would make a great pet.
A monkey would make a great pet.
A cat would make a great pet.
A dog would make a great pet.
A monkey would make a great pet.
Any of theseanimals would make a great pet!
4.3 建立數值列表
4.3.1 使用函式range()
- 函式range()可以輕鬆的讓我們生成一系列數字.
- 函式range()讓python從我們指定的位置開始數,並在到達我們指定的第二個值時停止(也就是包含左邊不包含右邊)
for value in range(1,6): print(value)
1
2
3
4
5
4.3.2 使用range()建立數字列表
- 要建立數字列表,可使用函式list()將rang()的結果直接轉化為列表,把rang()作為list()的引數.
# 打印出1-5 numbers = list(range(1,6)) print(numbers) # 打印出5-23的所有基數或者偶數 number = list(range(5,24,2)) # 函式range()從5開始數,然後不斷的+2,直到達到23 print(number) number = list(range(6,24,2)) # 函式range()從6開始數,不斷地+2,直到到達23 print(number)
[1, 2, 3, 4, 5]
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
[6, 8, 10, 12, 14, 16, 18, 20, 22]
# 打印出1-10的平方,使用for迴圈 numbers = list(range(1,11)) # 生成包含1-10的列表numbers for number in numbers: # 從列表numbers中取出值放入變數number裡面 #end = '空格'表示print完結後不換行,輸出一個空格,接著輸出print裡面需要列印的內容 print(number ** 2,end=' ') # 打印出變數number平方的值 # 打印出1-10的平方,並把結果放在列表裡面 print('\n') squares = [] for square in range(1,11): squares.append(square ** 2) print(squares)
1 4 9 16 25 36 49 64 81 100
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4.3.3 對數字列表執行簡單的統計計算
- 有幾個用於專門處理數字列表的python的函式可以讓我們輕鬆的找到列表的最大值丶最小值和總和
# min()獲取最小值,max()獲取最大值,sum()獲取所有元素的和 digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits)) print(max(digits)) print(sum(digits))
0
9
45
4.3.4 列表解析
- 列表解析將for迴圈和建立新元素的程式碼合併成一行,並自動附加新元素.
- 要使用這種語法:
- 1.指定一個列表名稱
- 2.指定一個左方括號,並定義一個表示式,用於生成我們要儲存到列表中的值
- 3.編寫一個for迴圈,用於給表示式提供值,在加上右方括號,for語句結束沒有冒號(:)
- 要使用這種語法:
squares = [value ** 2 for value in range(1,11)] print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
動手試一試
# 4-3 數到 20:使用一個 for 迴圈列印數字 1~20(含)。 for number in range(1,21): print(number,end = ' ') # 4-4 一百萬:建立一個列表,其中包含數字 1~1 000 000,再使用一個 for 迴圈將這些數字打印出來(如果輸出的時間太長,按 Ctrl + C 停止輸出,或關閉輸出視窗)。 numbers = list(range(1,1000001)) # print(numbers) '''4-5 計算 1~1 000 000 的總和:建立一個列表,其中包含數字 1~1 000 000,再使用min()和 max()核實該列表確實是從 1 開始,到 1 000 000 結束的。另外,對這個列表調 用函式 sum(),看看 Python 將一百萬個數字相加需要多長時間。''' numbers = list(range(1,1000001)) print(sum(numbers)) print(max(numbers)) print(min(numbers)) # 4-6 奇數:通過給函式range()指定第三個引數來建立一個列表,其中包含 1~20 的奇數;再使用一個 for 迴圈將這些數字都打印出來。 numbers = list(range(1,21,2)) for number in numbers: print(number,end = ' ') # 4-7 3 的倍數:建立一個列表,其中包含 3~30 內能被 3 整除的數字;再使用一個 for迴圈將這個列表中的數字都打印出來。 numbers = list(range(3,31,3)) for number in numbers: print(number,end = ' ')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 500000500000
1000000
1
1 3 5 7 9 11 13 15 17 19 3 6 9 12 15 18 21 24 27 30
'''4-8 立方:將同一個數字乘三次稱為立方。例如,在 Python 中, 2 的立方用 2**3 表示。請建立一個列表,其中包含前 10 個整數(即 1~10)的立方,再使用一個 for 循 環將這些立方數都打印出來。''' nums = list(range(1,11)) for num in nums: print(num ** 3,end = ' ') # 4-9 立方解析:使用列表解析生成一個列表,其中包含前 10 個整數的立方。 print("\n") nums = [num ** 3 for num in range(1,11)] print(nums)
1 8 27 64 125 216 343 512 729 1000
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4.4 使用列表的一部分
4.4.1 切片
- 要建立切片,可指定要使用的第一個元素和最後一個元素的索引.
- 和range()一樣,也是包含左邊不包含右邊
players = ['charles','martina','michale','florence','eli'] # 打印出列表的所有元素 print(players) # 打印出列表的前3個元素 print(players[0:3]) # 打印出列表的第2-4個元素 print(players[1:4]) # 如果沒有指定第一個索引,將會從頭開始列印到指定的第二個元素停止 print(players[:2]) # 如果沒有指定第二個索引,將會從指定位置列印到最後一個元素 print(players[2:])
['charles', 'martina', 'michale', 'florence', 'eli']
['charles', 'martina', 'michale']
['martina', 'michale', 'florence']
['charles', 'martina']
['michale', 'florence', 'eli']
4.4.2 遍歷切片
- 如果要遍歷列表的部分元素,可以在for迴圈中使用切片
players = ['charles','martina','michael','florence','eli'] print("Here are the first three players on my team:") for player in players[0:3]: print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
4.4.3 複製列表
- 要複製列表,可建立一個包含整個列表的切片,同時省略起始索引和終止索引([:])
my_foods = ['pizza','falafel','carrot cake'] # 複製列表 friend_foods = my_foods[:] print(friend_foods) # 像複製的列表末尾新增一個元素'ice cream friend_foods.append("ice cream") # 列印列表,不會影響另一個列表 print(friend_foods) print(my_foods)
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake', 'ice cream']
['pizza', 'falafel', 'carrot cake']
動手試一試
'''4-10 切片:選擇你在本章編寫的一個程式,在末尾新增幾行程式碼,以完成如下任務。 列印訊息“ The first three items in the list are:”,再使用切片來列印列表的前三個 元素。''' players = ['charles','martina','michale','florence','eli'] print("The first three items in the list are:",end = '') print(players[0:3]) # 列印訊息“ The last three items in the list are:”,再使用切片來列印列表末尾的三個元素。 print(players[-3:-1]) # 4-11 你的比薩和我的比薩:在你為完成練習 4-1 而編寫的程式中,建立比薩列表的副本,並將其儲存到變數 friend_pizzas 中,再完成如下任務。 pizzas = ['New York Style','Pan Pizza','Thick style'] friend_pizzas = pizzas[:] # 在原來的比薩列表中新增一種比薩。 pizzas.append('Chicago Style') # 在列表 friend_pizzas 中新增另一種比薩。 friend_pizzas.append('California Style') ''' 核實你有兩個不同的列表。為此,列印訊息“ My favorite pizzas are:”,再使用一個 for 迴圈來列印第一個列表;列印訊息“ My friend’s favorite pizzas are:”,再使 用一個 for 迴圈來列印第二個列表。核實新增的比薩被新增到了正確的列表中。''' print('\n') print(pizzas) print(friend_pizzas) print('\n') print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print('\n') print("My friend's favorite are:") for friend_pizza in friend_pizzas: print(friend_pizza)
The first three items in the list are:['charles', 'martina', 'michale']
['michale', 'florence']
['New York Style', 'Pan Pizza', 'Thick style', 'Chicago Style']
['New York Style', 'Pan Pizza', 'Thick style', 'California Style']
My favorite pizzas are:
New York Style
Pan Pizza
Thick style
Chicago Style
My friend's favorite are:
New York Style
Pan Pizza
Thick style
California Style
4.5 元組
- python裡面,我們把不能修改的值稱為不可變的,而不可變的列表被稱之為元組.
4.5.1 定義元組
- 元組看起來猶如列表,但使用圓括號()而不是方括號標識
dimensions = (200,50) # 定義了一個元組,使用的是圓括號而不是方括號 print(dimensions[1]) # 打印出元組的第2個元素 print(dimensions[0])
50
200
4.5.2 遍歷元組中的所有值
- 像列表一樣,也可以使用for迴圈來遍歷元組中的所有值
dimensions = (200,50) for dimension in dimensions: print(dimension)
200
50
4.5.3 修改元組變數¶
- 雖然不可以修改元組的元素,但是我們可以給儲存元組的變數賦值.
dimensions = (200,50) print(dimensions) dimensions = (400,100) print(dimensions)
(200, 50)
(400, 100)