【问题标题】:Iterating over nested for loop遍历嵌套的 for 循环
【发布时间】:2021-11-20 03:49:46
【问题描述】:

我正在尝试迭代多个值集合,并且代码按预期执行,但我想对每个 account_id 进行一次迭代,而不是对每个范围进行多次。

基本上我希望每个区域都与单个 account_id 相关联。 尤尔 > 11111111111; iad > 11111111222; gru > 99111111111.

例如,下面是我的代码。

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))

这就是我想要的。帐户 11111111222 和 99111111111 也具有相同的功能。

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

我希望输出与上面类似,每个区域与单个 account_id 相关联,而不是使用相同的帐户 ID 遍历每个区域。

有谁知道如何实现这个解决方案?

【问题讨论】:

  • 嗨 MXVII,你看到我的回答了吗?请给我一些反馈,干杯。

标签: python loops for-loop iteration counter


【解决方案1】:

使用 zip

    buildings = [i for i in range(1,90)]
    regions = ['yul', 'iad', 'gru']
    accounts = ['11111111111', '11111111222', '99111111111']
    
    for region, curr_account in zip(regions,accounts):
        print(f"{region} {building}  in account: {curr_account}")

每个区域按顺序对应一个帐户,它们位于列表中。
尤尔:11111111111
iad : 11111111222
格鲁:11111111222

【讨论】:

    【解决方案2】:

    您可以使用zip将列表对应的索引绑定在一起,得到您的解决方案

    # 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多