Milhouse Milhouse - 2 years ago 105
Python Question

Combine two loop into one

I have three different loops in my code but I am wondering if there is a way to combine two of them where it only loops through once. My code is below:

for x in groups:
A bunch of code that produces the following...

I then loop through two loops below. These are the ones I'm trying to combine.

for x, frame in frames.items():
more unrelated code

for x, highc in highcs.items():

The final two loops are really just creating excel workbooks using xlsxwriter. The first loop creates the workbook and inputs dataframes from frames[x] onto the worksheets. Then highc just goes back over the same sheets and adds new dataframes.

Answer Source

frames and highcs are the same length, you can use zip() to iterate them at once:

for (f,frame), (h, highc) in zip(frames.items(), highcs.items()):
    # do your work here


This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.The returned list is truncated in length to the length of the shortest argument sequence.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download