5.Loops and List Comprehensions
Loops
循環是一種重復執行某些代碼的方法。
[1]
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] for planet in planets:print(planet, end=' ') # print all on same line Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune注意for循環的簡單性:我們指定我們想要使用的變量,我們想要循環的序列,并使用“in”關鍵字以直觀和可讀的方式將它們鏈接在一起。
“in”右側的對象可以是支持迭代的任何對象。 基本上,如果它可以被認為是一個序列或事物的集合,可以循環它。 除了列表,我們也可以迭代元組中的元素:
[2]
multiplicands = (2, 2, 2, 3, 3, 5) product = 1 for mult in multiplicands:product = product * mult product 360甚至還可以迭代字符串中的每個字母:
[3]
s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.' msg = '' # print all the uppercase letters in s, one at a time for char in s:if char.isupper():print(char, end='') HELLOrange()
range()是一個返回數字序列的函數。 事實證明,編寫循環非常有用。
例如,如果我們想重復一些動作5次:
[4]
for i in range(5):print("Doing important work. i =", i) Doing important work. i = 0 Doing important work. i = 1 Doing important work. i = 2 Doing important work. i = 3 Doing important work. i = 4你可能認為range(5)返回列表[]?1,? 2, 3,? 4,? 5] ,真是情況有點復雜。
[5]
r = range(5) r range(0, 5)range返回“range object”。 它的行為很像列表(它是可迭代的),但不具備所有相同的功能。 正如我們在上一個教程中看到的那樣,我們可以在像r這樣的對象上調用help()來查看該對象的Python文檔,包括它的所有方法。?
[6]
help(range)就像我們可以使用int(),float()和bool()將對象轉換為另一種類型一樣,我們可以使用list()將類似列表的東西轉換為列表,這表示更熟悉(和有用) 的表示:
[7]
list(range(5)) [0, 1, 2, 3, 4]請注意,范圍從零開始,按照慣例,范圍的頂部 不包括在輸出中。 range(5)給出0到5但不包括5的數字。
這可能看起來像是一種奇怪的方式,但文檔(通過help(range))提到的原因是:
range(4)產生0,1,2,3。這些正是4個元素列表的有效索引。
因此對于任何列表L,for i in range(len(L)):將迭代其所有有效索引。
[8]
nums = [1, 2, 4, 8, 16] for i in range(len(nums)):nums[i] = nums[i] * 2 nums [2, 4, 8, 16, 32]這是通過索引迭代列表或其他序列的經典方法。
另外:for i in range(len(L)):類似于其他語言中的for (int i = 0; i < L.length; i++)
enumerate
for foo in x 通過元素循環遍歷列表,而for i in range(len(x))通過索引循環遍歷列表。 如果你想兩個都做怎么辦?
輸入枚舉函數,這是Python隱藏的寶石之一:
[9]
def double_odds(nums):for i, num in enumerate(nums):if num % 2 == 1:nums[i] = num * 2x = list(range(10)) double_odds(x) x [0, 2, 2, 6, 4, 10, 6, 14, 8, 18]給定一個列表,枚舉返回一個對象,該對象通過列表的值和索引進行迭代。
(與range()函數一樣,它返回一個可迭代對象。要將其內容作為列表查看,我們可以在其上調用list()。)
[10]
list(enumerate(['a', 'b']))[(0, 'a'), (1, 'b')]我們可以看到,我們迭代的東西是元組。 這有助于解釋for i,num語法。 我們正在“解包”元組,就像上一個教程中的示例一樣:
[11]
x = 0.125 numerator, denominator = x.as_integer_ratio()我們可以在迭代元組集合時使用這種解包語法。
[12]
nums = [('one', 1, 'I'),('two', 2, 'II'),('three', 3, 'III'),('four', 4, 'IV'), ]for word, integer, roman_numeral in nums:print(integer, word, roman_numeral, sep=' = ', end='; ') 1 = one = I; 2 = two = II; 3 = three = III; 4 = four = IV;這與下面的代碼等價:
[13]
for tup in nums:word = tup[0]integer = tup[1]roman_numeral = tup[2]print(integer, word, roman_numeral, sep=' = ', end='; ') 1 = one = I; 2 = two = II; 3 = three = III; 4 = four = IV;while loops
Python中另一類循環是while循環:
[14]
i = 0 while i < 10:print(i, end=' ')i += 1 0 1 2 3 4 5 6 7 8 9while循環的參數被計算為布爾語句,并且直到語句求值為False時停止循環。
List comprehensions
列表解析是Python中最受歡迎和獨特的功能之一,理解它的最簡單的方式就是看一下例子:
[15]
squares = [n**2 for n in range(10)] squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]這里有一個不用列表解析的例子,效果是一樣的:
[16]
squares = [] for n in range(10):squares.append(n**2) squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]我們也增加if條件:
[17]
short_planets = [planet for planet in planets if len(planet) < 6] short_planets ['Venus', 'Earth', 'Mars'](如果您熟悉SQL,可能會將其視為“WHERE”子句)
以下是使用if條件進行過濾并對循環變量應用某些變換的示例:
[18]
# str.upper() returns an all-caps version of a string loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6] loud_short_planets ['VENUS!', 'EARTH!', 'MARS!']人們通常把這些寫在一行里,但是如果分成3行來寫,結果會變得很清晰:
[19]
[planet.upper() + '!' for planet in planets if len(planet) < 6 ] ['VENUS!', 'EARTH!', 'MARS!']繼續SQL類比,您可以將這三行視為SELECT,FROM和WHERE
左邊的表達式在技術上不必涉及循環變量(盡管它不是很常見)。 您認為以下表達式將做什么??
[20]
[32 for planet in planets]列表解析與我們看到的一些函數(如min,max,sum,len和sorted)相結合,可以為一些問題提供一些令人印象深刻的單行解決方案,否則這些問題需要幾行代碼。
例如,最后一個練習包括一個腦力激蕩器,要求你編寫一個函數來計算列表中的負數,而不使用循環(或我們沒有看到的任何其他語法)。 現在我們可以解決問題,因為我們的武器庫中有循環:
[21]
def count_negatives(nums):"""Return the number of negative numbers in the given list.>>> count_negatives([5, -1, -2, 0, 3])2"""n_negative = 0for num in nums:if num < 0:n_negative = n_negative + 1return n_negative這有一個使用列表解析的辦法:
[22]
def count_negatives(nums):return len([num for num in nums if num < 0])很好吧?
好吧,如果我們關心的是最小化代碼的長度,那么第三種解決方案仍然更好!
[23]
def count_negatives(nums):# Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of # Python where it calculates something like True + True + False + True to be equal to 3.return sum([num < 0 for num in nums])這些解決方案中哪一個是“最好的”完全是主觀的。 使用較少的代碼解決問題總是很好,但值得記住以下來自The Zen of Python的內容:
- 可讀性很重要。
- 顯式優于隱式。
count_negatives的最后一個定義可能是最短的,但閱讀代碼的其他人是否理解它是如何工作的?
編寫Pythonic代碼并不意味著永遠不會使用for循環!
Your turn!
轉到練習筆記本,進行循環和列表解析的練習。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的5.Loops and List Comprehensions的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lsasss.exe是什么进程 有什么用
- 下一篇: CS231n(1):图片分类笔记与KNN