首页 > 解决方案 > python嵌套for循环通过第一个循环添加增量值

问题描述

想象一下这种情况:

cable1 = ['label_11','label_12','label_13']
cable2 = ['label_21','label_22','label_21']
cable3 = ['label_31','label_32','label_33']
cables = [cable1,cable2,cable3]
number = 0

for cable in cables:
    number += 1
    for label in cable:
        if label.find('3') != -1:
            label = str(number)+'_'+label
            print(f'label: {label}')

印刷:

label: 1_label_13
label: 3_label_31
label: 3_label_32
label: 3_label_33

代替:

label: 1_label_13
label: 2_label_31
label: 2_label_32
label: 2_label_33

如何通过电缆进行第三次迭代以成为 2 标签?

标签: pythonincrementnested-for-loop

解决方案


您可以在使用环路之前过滤掉电缆:

cables = [cable for cable in cables if '3' in ''.join(cable)]

完整样本:

cable1 = ['label_11','label_12','label_13']
cable2 = ['label_21','label_22','label_21']
cable3 = ['label_31','label_32','label_33']
cables = [cable1,cable2,cable3]
cables = [cable for cable in cables if '3' in ''.join(cable)]
number = 0

for cable in cables:
    number += 1
    for label in cable:
        if label.find('3') != -1:
            label = str(number)+'_'+label
            print(f'label: {label}')

label: 1_label_13
label: 2_label_31
label: 2_label_32
label: 2_label_33

推荐阅读