【问题标题】:python nested for loop add incremented value by first looppython嵌套for循环通过第一个循环添加增量值
【发布时间】:2021-04-29 19:41:21
【问题描述】:

想象一下这种情况:

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 标签?

【问题讨论】:

    标签: python increment nested-for-loop


    【解决方案1】:

    这是因为您在每次迭代中增加了变量 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.
    

    【讨论】:

    • 在循环之前注意数字 = 1,这样就完美了!非常感谢!
    【解决方案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
    

    【讨论】:

    • 如果只需要进行一次检查,这对我来说是最好的解决方案。在我的情况下,我实际上需要多次检查,所以 Nk03 的解决方案更适合我的情况......
    • @novski [cable for cable in cables if '3' in ''.join(cable)] 也可以包含多个检查:例如[cable for cable in cables if ('3' in ''.join(cable)) | ('2' in ''.join(cable))]
    • 完全正确!但是如何设计那行代码的样式是有待商榷的。
    猜你喜欢
    • 2013-08-04
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    相关资源
    最近更新 更多