Search code examples
pythonloopsfor-loopiterationcounter

Iterating over nested for loop


I am trying to iterate over multiple collections of values and the code is performing as expected except I would like to iterate over each account_id once, instead of multiple times for each reach.

Essentially I want each region to correlate with a single account_id. YUL > 11111111111; iad > 11111111222; gru > 99111111111.

For example here's my code below.

buildings = [i for i in range(1,90)]
regions = ['yul', 'iad', 'gru']
accounts = ['11111111111', '11111111222', '99111111111']

def testing(buildings, regions):
    accountIdx = -1
    for account in accounts:          
        if accountIdx < 0:
            print('First iteration')
        accountIdx += 1
        curr_account = accounts[accountIdx] # Counter variable + after each iteration
        print(curr_account)
        for region in regions:               
            for building in buildings:
               print('%s%s in account:%s'%(region, building,curr_account))

This is what I would like. It has the same thing for accounts 11111111222 and 99111111111 too.

Current Output: iad**<1-89>** in account:11111111111 
                gru**<1-89>** in account: 11111111111
                yul**<1-89>** in account: 11111111111





Expected Output: iad**<1-89>** in account:11111111111 
                 gru**<1-89>** in account: 11111111222
                 yul**<1-89>** in account: 99111111111

I would like the output to be like this above, with each region correlating with a single account_id, instead of iterating over each region with the SAME account Id.

Does anyone know how this solution can be achieved?


Solution

  • you can use zip to bind the corresponding index of list together and achive your solution

    # your code goes here
    buildings = [i for i in range(1,90)]
    regions = ['yul', 'iad', 'gru']
    accounts = ['11111111111', '11111111222', '99111111111']
    
    def testing(buildings, regions):
    
        for account, building, region in zip(accounts, buildings, regions):
                   print('%s%s in account:%s'%(region, building, account))
              
    testing(buildings, regions)