python - 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 标签?
解决方案
您可以在使用环路之前过滤掉电缆:
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
推荐阅读
- django - 为什么 Django Visual Studio 代码中的前端更改不会立即在浏览器中执行
- c# - 与排序列表的数据绑定
- javascript - Ajax 调用成功函数触发两次
- javascript - React.js document.querySelectorAll() 不返回任何内容
- java - Jira 无法使用 Seraph SSO DefaultAuthenticator 更新上次登录时间
- c# - xamarin.ios 上的视图之间的翻译动画 [已解决]
- html - 如何在边框线之后(不在边框内)将图像附加到边框
- c++ - 与函数指针、__cdecl 和模板混淆
- python - Python函数不承认我的输入
- .net - 在 Asp.net 微服务中运行子 Vue.js 应用程序时出错