You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多列表遍历结合条件判断实现指定格式输出问题求解

问题解决方法

你代码的核心错误是zip()参数顺序和循环接收变量的匹配关系错位:
zip(values, nodes, cells)返回的三元组顺序是(values列表元素, nodes列表元素, cells列表元素),你用v, c, n接收的话,会把nodes元素赋值给c、cells元素赋值给n,和你需要的使用逻辑完全相反。

修正方案1(更推荐,变量名和语义对应,可读性高)

调整循环接收变量的顺序,同时用f-string格式化输出,避免逗号拼接可能带来的空格控制问题:

dicts = {0:1, 1:1, 2:1}
values = list(dicts.values()) 

cells = ['ABC', 'DEF', 'GHI']
nodes = ['123', '456', '789']

for v, n, c in zip(values, nodes, cells):
    if v == 1:
        print(f'Some Text {n} Some Text {n} text {c} Some Text')

修正方案2(不修改循环变量,调整zip参数顺序)

如果不想改动现有循环变量名,调整zip的参数顺序即可:

dicts = {0:1, 1:1, 2:1}
values = list(dicts.values()) 

cells = ['ABC', 'DEF', 'GHI']
nodes = ['123', '456', '789']

for v, c, n in zip(values, cells, nodes):
    if v == 1:
        print('Some Text ', n, ' Some Text ', n, ' text ', c, ' Some Text')

两种方案运行后均可得到你期望的输出:

Some Text 123 Some Text 123 text ABC Some Text
Some Text 456 Some Text 456 text DEF Some Text
Some Text 789 Some Text 789 text GHI Some Text

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:06:07