Apr-14-2019, 08:48 AM
The function
The nested iteration you do, is a product.
If you use the
The complexity is shifted into the product function and you get i and j.
The second argument defines the start value of enumeration.
Tuple unpacking is used, to assign i and j.
Regular example of enumeration:
If you remove the parenthesis around (first, second), you'll get
itertools.product
is very handy for products.The nested iteration you do, is a product.
If you use the
product
function, you can remove the nested loop.The complexity is shifted into the product function and you get i and j.
from itertools import product import xlsxwriter workbook = xlsxwriter.Workbook('Test.xlsx') worksheet = workbook.add_worksheet('MySheet') col = 0 range4 = range(4) matrix = product(range4, range4) for row, (i, j) in enumerate(matrix, start=1): worksheet.write(row, col, i) worksheet.write(row, col+1, j) workbook.close()The
enumerate
function enumerates any iterable.The second argument defines the start value of enumeration.
Tuple unpacking is used, to assign i and j.
Regular example of enumeration:
for row, i in enumerate(range(10), start=1): print(row, i)I call it nested tuple unpacking.
iterable = [(1,2), (3,4), (5,6), (7,8)] # 2 for row, (first, second) in enumerate(iterable, start=1): print(row, first, second)First the yielded iterable from for is assigned to row, then the second element is unpacked and assigned to first and second.
If you remove the parenthesis around (first, second), you'll get
Error:ValueError: not enough values to unpack, (expected 3, got 2)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!