Skip to content

Commit 40574da

Browse files
authored
Add reshape() recipe to demonstrate a use case for batched() and chained.from_iterable() (gh-113198)
1 parent 00d2b6d commit 40574da

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

Doc/library/itertools.rst

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,10 +1036,15 @@ The following recipes have a more mathematical flavor:
10361036
# sum_of_squares([10, 20, 30]) -> 1400
10371037
return math.sumprod(*tee(it))
10381038
1039-
def transpose(it):
1040-
"Swap the rows and columns of the input."
1039+
def reshape(matrix, cols):
1040+
"Reshape a 2-D matrix to have a given number of columns."
1041+
# reshape([(0, 1), (2, 3), (4, 5)], 3) --> (0, 1, 2), (3, 4, 5)
1042+
return batched(chain.from_iterable(matrix), cols)
1043+
1044+
def transpose(matrix):
1045+
"Swap the rows and columns of a 2-D matrix."
10411046
# transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)
1042-
return zip(*it, strict=True)
1047+
return zip(*matrix, strict=True)
10431048
10441049
def matmul(m1, m2):
10451050
"Multiply two matrices."
@@ -1254,6 +1259,22 @@ The following recipes have a more mathematical flavor:
12541259
>>> sum_of_squares([10, 20, 30])
12551260
1400
12561261

1262+
>>> list(reshape([(0, 1), (2, 3), (4, 5)], 3))
1263+
[(0, 1, 2), (3, 4, 5)]
1264+
>>> M = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
1265+
>>> list(reshape(M, 1))
1266+
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)]
1267+
>>> list(reshape(M, 2))
1268+
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
1269+
>>> list(reshape(M, 3))
1270+
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
1271+
>>> list(reshape(M, 4))
1272+
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
1273+
>>> list(reshape(M, 6))
1274+
[(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)]
1275+
>>> list(reshape(M, 12))
1276+
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)]
1277+
12571278
>>> list(transpose([(1, 2, 3), (11, 22, 33)]))
12581279
[(1, 11), (2, 22), (3, 33)]
12591280

0 commit comments

Comments
 (0)