python迭代-如何在一個for語句中迭代多個可迭代對象


如何在一個for語句中迭代多個可迭代對象

問題舉例

(1)某班學生期末考試成績,語文,數學,英語分別存儲在3個列表中,同時迭代三個列表,計算每個學生的總分

(2)某年級有4個班,某次考試每班英語成績分別存儲在4個列表中,一次迭代每個列表,統計全學年成績高於90分的人數

 

解決思路

(1)使用內置函數zip,它能將多個可迭代對象合並,每次迭代返回一個元組(並行)

(2)使用標准庫中itertools.chain,它能將多個可迭代對象連接(串行)

 

代碼(並行)

from random import randint
chinese = [randint(60, 100) for _ in range(20)]
math = [randint(60, 100) for _ in range(20)]
english = [randint(60, 100) for _ in range(20)]

res1 = []
for s1, s2, s3 in zip(chinese, math, english):
    res1.append(s1 + s2 + s3)

print(res1)

res2 = [sum(s) for s in zip(chinese, math, english)]
res3 = list(map(sum, zip(chinese, math, english)))
res4 = list(map(lambda s1, s2, s3: s1 + s2 + s3, chinese, math, english))
print(res2)
print(res3)
print(res4)

print("\nmap and zip do same function")
list1 = list(map(lambda *args: args, chinese, math, english))
list2 = list(zip(chinese, math, english))
print(list1 == list2)

 

代碼(串行)

from random import randint
from itertools import chain

c1 = [randint(60, 100) for _ in range(20)]
c2 = [randint(60, 100) for _ in range(20)]
c3 = [randint(60, 100) for _ in range(23)]
c4 = [randint(60, 100) for _ in range(25)]
print(c1)
print(c2)
print(c3)
print(c4)
nums = len([x for x in chain(c1, c2, c3, c4) if x > 90])
print(nums)

 

參考資料:python3實用編程技巧進階


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM