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

时间:2021-07-09 09:07:01

标签: python for-loop

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

1 个答案:

答案 0 :(得分:1)

你大概想要这个:

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

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

相关问题