while循环不生成输出

时间:2015-04-10 04:53:08

标签: python python-3.x while-loop

以下代码有什么问题:

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
        i += 1

预期产出:

2011.txt
2011.txt
2011.txt

3 个答案:

答案 0 :(得分:4)

如果if条件为false,则表示您没有递增i

这样的最后一行。

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
    i += 1

最好只使用for循环(告别“off-by-one”错误)

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
for item in years:
    if a.endswith(item + '.txt'):
        print(item + '.txt')

如果您还需要循环计数器,请使用enumerate

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
for i, item in enumerate(years):
    if a.endswith(item + '.txt'):
        print(item + '.txt')

答案 1 :(得分:0)

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
for i in years:
    if a.endswith(i + '.txt'):
        print(i + '.txt')

当条件为假时,您没有递增i

使用for或类似的内容

O/p 

2011.txt
2011.txt
2011.txt

答案 2 :(得分:0)

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
    i += 1