为什么我不能在forloop中打印每个结果?

2024-05-14 08:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: orinforlenifrangeflowtemp
1条回答
网友
1楼 · 发布于 2024-05-14 08:33:50

你大概想要这个:

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

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

相关问题 更多 >

    热门问题