3-5 1つのfor文で複数の反復可能オブジェクトを反復する方法
1603 ワード
実例:1.あるクラスの学生の期末試験の成績、国語、数学、英語はそれぞれ3つのリストに格納され、同時に3つのリストを反復し、各学生の総得点(並列)を計算する.
2.ある学年は4つのクラスがあり、ある試験の各クラスの英語の成績はそれぞれ4つのリストに格納され、各リストを順次反復し、全学年の成績が90点を超える人数を統計する(シリアル)
ソリューション:パラレル:組み込み関数zipを使用して、複数の反復可能なオブジェクトをマージし、反復するたびにメタグループシリアルを返します.標準ライブラリのitertoolsを使用します.chain、複数の反復可能なオブジェクトを接続できます
シナリオ1:
シナリオ2:
2.ある学年は4つのクラスがあり、ある試験の各クラスの英語の成績はそれぞれ4つのリストに格納され、各リストを順次反復し、全学年の成績が90点を超える人数を統計する(シリアル)
ソリューション:パラレル:組み込み関数zipを使用して、複数の反復可能なオブジェクトをマージし、反復するたびにメタグループシリアルを返します.標準ライブラリのitertoolsを使用します.chain、複数の反復可能なオブジェクトを接続できます
シナリオ1:
zip(iter1 [,iter2 [...]]) --> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
from random import randint
count = 30 #
chinese = [randint(50,100) for _ in range(count)]
math = [randint(50,100) for _ in range(count)]
english = [randint(50,100) for _ in range(count)]
# : :
for i in range(count):
print(i,chinese[i],math[i],english[i],)
# :zip
for c,m,e in zip(chinese,math,english):
print(c,m,e)
シナリオ2:
chain(*iterables) --> chain object
Return a chain object whose .__next__() method returns elements from the
first iterable until it is exhausted, then elements from the next
iterable, until all of the iterables are exhausted.
from itertools import chain
# 4
cls1 = [randint(60,100) for _ in range(30)]
cls2 = [randint(60,100) for _ in range(30)]
cls3 = [randint(60,100) for _ in range(30)]
count = 0
for x in chain(cls1,cls2,cls3):
if x >= 90:
count += 1
print(count)