python入门问题 IndexError: list index out of range,求大神帮助,谢谢先
发布网友
发布时间:2022-06-07 16:54
我来回答
共2个回答
热心网友
时间:2023-10-22 11:03
f = open('input.txt', 'r')
a = 0
nr_of_lines = sum(1 for line in f)
for a in range(nr_of_lines):
if a % 2 == 1:
b = f.readlines()[a]
print b
a = a + 1
f.close()
写的些什么。。。简直是c风格的python。。。。
a = 0 不要写。。。
f = open('input.txt')
for i,line in enumerate(f):
if (i + 1) % 2 == 0:
print line
f.close()
热心网友
时间:2023-10-22 11:03
# encoding: utf-8
'''
Created on 2015年5月7日
@author: 传庆
'''
'''
f = open('input.txt', 'r')
a = 0
# 执行完下边的代码之后文件自动关闭了,导致f.readlines()读出的列表是空的,
# 你可以自行打印其内容进行查看,再说a % 2 == 1取的是奇数行不是偶数.
nr_of_lines = sum(1 for line in f)
print f.readlines()
print nr_of_lines
for a in range(nr_of_lines):
if a % 2 == 1:
b = f.readlines()[a]
print b
# for cycle do inc auto.
#a = a + 1
f.close()
'''
# you can code like below
flag = False
with open('input.txt', 'r') as f:
for line in f:
if flag:
print line
flag = False
else:
flag = True