python—为什么我不能在for循环中打印每个结果?

tkclm6bt  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(360)
strs = ["flower","flow","flight","fluea","flfjdkl","f"]
temp = strs[0]

for i in range(1, len(strs)):
    for j in range(len(temp)):
        if j >= len(strs[i]) or strs[i][j] != temp[j]:
            temp = temp[:j]
            print(temp)
            break

我想打印变量 temp 无论何时结束 if 陈述但是,它只会在任何时候打印 temp 变化。
例如,该代码的结果是:

flow
fl
f

但我希望结果是:

flow
fl
fl
fl
f
50few1ms

50few1ms1#

你大概想要这个:

strs = ["flower","flow","flight","fluea","flfjdkl","f"]
temp = strs[0]

for i in range(1, len(strs)):
    for j in range(len(temp)):
        if j >= len(strs[i]) or strs[i][j] != temp[j]:
            temp = temp[:j]
            break 
    print(temp) 

flow
fl
fl
fl
f

这将为每个外部循环迭代(列表中的每个单词)打印剩余的公共前缀。

相关问题