天天看點

Python學習筆記:1.3.3 for循環

本文是學習齊偉老師的《python全棧工程師》課程的筆記,歡迎學習交流。同時感謝齊老師的精彩傳授!

一、課程目标
  • 掌握 for 循環語句的結構
  • 掌握清單解析的使用方法
  • 在程式中應用 for 循環語句
二、詳情解讀

1.基本形式:

Python學習筆記:1.3.3 for循環
Python學習筆記:1.3.3 for循環
Python學習筆記:1.3.3 for循環

注意:用于for循環的對象必須是可疊代對象!!

判斷對象是否是可疊代的:hasattr(obj, ‘iter’)或者 用collections子產品

Python學習筆記:1.3.3 for循環

注意:python版本3.8以後,需要用 import collections.abc

Python學習筆記:1.3.3 for循環

2.相關函數:

  • range():

    用range建立清單時,清單中被使用的值才會占用記憶體空間,清單中沒有被使用的值不會占用記憶體空間

    Python學習筆記:1.3.3 for循環
  • zip():
  • Python學習筆記:1.3.3 for循環
  • enumerate():
    Python學習筆記:1.3.3 for循環

    3.清單解析:

    清單解析(list comprehension),又譯為”清單推導“

    Python學習筆記:1.3.3 for循環
    4.其他解析:
    Python學習筆記:1.3.3 for循環

    5.例題講解:

    例題1:

  • 統計如下字元串中每個單詞的數量。

    – song = “when I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountains YOu raise me up to walk on stormy sears I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains Your raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains”

song = "when I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountains YOu raise me up to walk on stormy sears I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains Your raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains"
slst = song.split()
d = {}

for word in slst:
	word = word.lower()
	if word in d:
		d[word] += 1
	else:
		d[word] = 1
print(d)
           

運作效果圖:

Python學習筆記:1.3.3 for循環

例題2:

  • 如下字典,将鍵和值對換,即鍵作為值,值作為鍵。

    – d = {‘book’: [‘python’, ‘datascience’], ‘author’: ‘laoqu’, ‘publisher’: ‘phei’}

小編參考:

d = {'book': ['python', 'datascience'], 'author': 'laoqu', 'publisher': 'phei'}
new_d = {}
for k, v in d.items():
    # 字典中的鍵必須是不可變的,是以将清單轉換為元組
    if type(v) == list:
        v = tuple(v)
    new_d[v] = k
print(new_d)
           

運作效果圖:

Python學習筆記:1.3.3 for循環

老師參考:

import collections.abc
d = {'book': ['python', 'datascience'], 'author': 'laoqu', 'publisher': 'phei'}
dd = {}
for k, v in d.items():
    if isinstance(v, collections.abc.Hashable):
        dd[v] = k
    else:
        dd[tuple(v)] = k
print(dd)

# 方法二:用字典推導式
ddd = {v if isinstance(v, collections.abc.Hashable)
      else tuple(v): k for k, v in d.items()}
print(ddd)
           

運作效果跟上面的一樣,老師這個判斷是否是可疊代對象更好點。

三、課程小結
  • 學習了 for 循環
  • 學習了清單解析和其他解析
四、作業:
  • 有字元串 : Life is short You need python

    – 顯示每個單詞大寫和小寫兩種狀态

    – 統計每個單詞的長度

小編參考:

s = 'Life is short You need python'
print(s.upper())
s_lower = s.lower()
print(s_lower)
# 去除重複元素後再統計
slst = list(set(s_lower.split()))
dd = {}
for i in slst:
	dd[i] = len(i)
print(dd)
           

運作效果圖

Python學習筆記:1.3.3 for循環

繼續閱讀