python 嵌套 for 循环通过第一个循环添加增量值

python nested for loop add incremented value by first loop

想象一下这种情况:

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

我怎样才能使 cable 上的第三次迭代成为 2 标签?

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

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

这是因为您在每次迭代中都增加了变量 number 的计数。您可以通过标志控制此增量。这样的事情可能会有所帮助 -

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 = 1

for cable in cables:
    flag = 0
    for label in cable:
        if label.find('3') != -1:
            label = str(number)+'_'+label
            print(f'label: {label}')
            flag = 1
    if flag:
        number += 1 # only increase the value if the item is found.