Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iteration with 2 Variables
#8
The function 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!
Reply


Messages In This Thread
Iteration with 2 Variables - by punksnotdead - Apr-10-2019, 04:54 PM
RE: Iteration with 2 Variables - by ichabod801 - Apr-10-2019, 05:46 PM
RE: Iteration with 2 Variables - by punksnotdead - Apr-12-2019, 01:02 PM
RE: Iteration with 2 Variables - by ichabod801 - Apr-12-2019, 04:47 PM
RE: Iteration with 2 Variables - by punksnotdead - Apr-12-2019, 04:58 PM
RE: Iteration with 2 Variables - by Yoriz - Apr-12-2019, 05:03 PM
RE: Iteration with 2 Variables - by punksnotdead - Apr-13-2019, 08:33 AM
RE: Iteration with 2 Variables - by DeaD_EyE - Apr-14-2019, 08:48 AM
RE: Iteration with 2 Variables - by punksnotdead - Apr-14-2019, 11:01 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020