列表簡介(3)
操作列表
經常會有遍歷列表的所有元素,對每個元素執行相同的操作
eg: 在遊戲中可能需要將每個界面元素平移相同的距離;
對於包含數字的列表,可能需要對每個元素執行相同的統計運算
在網站中,可能需要顯示文章列表中的每個標題等等
使用for循環
eg:
magicians = [‘alice‘, ‘david‘, ‘carolina‘]
for magician in magicians:
print(magician)
============================================
output:
alice
david
carolina
========================================
定義一個for循環,讓列表magicians中取出一個名字,
並將其存儲在變量magician中,最後,讓python打印前面存儲
到變量magician中的名字
對列表中的每個元素,都將執行循環指定的步驟,而不管列表包含多少個元素
如果列表包含一百萬個元素,Python就重復執行指定的步驟一百萬次,且通常
速度非常快。
編寫for循環時,對於用於存儲列表中每個值得臨時變量,可指定任何名稱。
but 選擇描述單個列表元素的有意義的名稱大有幫助。
eg:對於小貓列表、小狗列表和一般性列表,像下列編寫for循環是一個不錯的選擇
for cat in cats:
for dog in dogs:
for item in list_of_items:
4.1 創建數值列表:
列表非常適用存儲數字集合,而Python提供了很多工具,可幫助你高效地處理數字列表
4.1.1 使用函數range()
Python函數range()讓你輕松地生成一系列的數字,
eg:
for value in range(1, 5):
print(value)
========================
1
2
3
4
=====================
python的特性是左閉右開
4.1.2 使用range()創建數字列表
要創建數字列表,可使用函數list()將range()的結果直接轉換為列表。
如果將range()作為list()的參數,輸出將為一個數字列表。
將數字轉換為一個列表,可使用list():
numbers = list(range(1, 6))
print(numbers)
===========================
output:
[1, 2, 3, 4, 5]
===========================
使用函數range() 可指定步長
eg:
打印1~10內的偶數:
even_numbers = list(range(2, 11, 2))
print(even_numbers)
======
output:
[2, 4, 6, 8, 10]
使用函數range()幾乎能創建任何需要的數字集:
eg:
如何創建前10個整數的平方呢?
兩個星號(**)表示乘方運算
eg:
squares = []
for value in range(1, 11):
squares.append(value**2)
print(squares)
==========
output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
=====================================
4.1.3 對數字列表執行簡單的統計計算
有專門用於處理數字列表的Python函數
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(min(digits))
print(max(digits))
print(sum(digits))
===================
output:
1
10
55
=====================
4.1.4 列表解析
前面介紹的生成列表squares的方式包含三四行代碼,
列表解析讓你只需編寫一行代碼就能生成相同的列表
列表解析將for循環和創建新元素的代碼合並成一行,
並自動附加新元素
eg:
squares = [value**2 for value in range(1,11)]
print(squares)
============================
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
=================
使用這種語法,首先指定一個描述性地列表名,如squares;
然後,指定一個左方括號,並定義一個表達式,用於生成要存儲
到列表中的值,在這個示例中,表達式為value**2, 接下來
編寫一個for循環,用於給表達式提供值,再加上右方括號,
在這個示例中,for循環為for value in range(1,11)
它將值1~10提供給表達式value**2, 請註意,for語句末尾沒有冒號
當覺得編寫三四行代碼來生成列表有點繁復時,就應考慮創建列表解析
4.2 使用列表的一部分
4.2.1 切片
要創建切片, 可指定要使用的第一元素的索引和最後一個元素的索引加1,
與函數range()一樣,
eg:
輸出列表中的前三個元素,需要指定索引0~3, 這將輸出分別為0、1、2的元素
eg:
players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]
print(players[0:3])
print(players[:4])
print(players[2:])
print(players[-3:])
print(players[:])
=======================
output:
[‘charles‘, ‘martina‘, ‘michael‘]
[‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘]
[‘michael‘, ‘florence‘, ‘eli‘]
[‘michael‘, ‘florence‘, ‘eli‘]
[‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]
======================
players[:4]沒有指定第一個索引,python將自動從列表開頭開始
要讓切片終止於列表末尾,也可使用類似的語法,
players[2:]從第三個元素到列表末尾的所有元素
負數索引返回離列表末尾相應距離的元素,因此可以輸出列表末尾的任何切片
輸出最後三個元素,使用切片players[-3:]
players[:]輸出從開頭到結尾
4.2.2 遍歷切片
如遍歷列表的部分元素,可在for循環中使用切片。
eg:
players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]
for player in players[:3]:
print(player.title())
=======
output:
Charles
Martina
Michael
=========
這裏只遍歷前三個元素:
在很多情況下,切片都很有用,
eg:編寫遊戲時,可以在玩家退出遊戲時將其最終得分加入到一個列表中
為獲得三個最高得分,可將列表按降序排列,再創建一個只包含前三個得分
的切片,處理數據時,可使用切片進行批量處理,編寫Web應用程序時,
可使用切片來分頁顯示信息,並將每頁顯示數量合適的信息
4.2.2 復制列表
要復制列表,可創建一個包含整個列表的切片,
eg:
my_foods = [‘pizza‘, ‘falafel‘, ‘carrot cake‘]
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append(‘cannoli‘)
friend_foods.append(‘ice cream‘)
print(my_foods)
print(friend_foods)
=====
output:
[‘pizza‘, ‘falafel‘, ‘carrot cake‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘, ‘cannoli‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘, ‘ice cream‘]
=======================
在不指定任何索引的情況下從列表my_foods中提取一個切片,從而創建這個列表的副本
再將副本存儲到變量friend_foods中,打印每個列表後,發現包含元素相同
添加元素發現都包含在正確的列表中
如果只是簡單地將列表賦值給另一個列表將不能得到兩個列表
eg:
不適用切片的情況下復制列表
my_foods = [‘pizza‘, ‘falafel‘, ‘carrot cake‘]
friend_foods = my_foods
print(my_foods)
print(friend_foods)
my_foods.append(‘cannoli‘)
friend_foods.append(‘ice cream‘)
print(my_foods)
print(friend_foods)
=====================
output:
[‘pizza‘, ‘falafel‘, ‘carrot cake‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘, ‘cannoli‘, ‘ice cream‘]
[‘pizza‘, ‘falafel‘, ‘carrot cake‘, ‘cannoli‘, ‘ice cream‘]
=======================
這種語法實際上是讓python將新變量friend_foods關聯到包含在my_friends中的列表
因此這兩個變量都指向同一個列表
輸出表明,這兩個列表是相同的
列表簡介(3)