Python 3.x 关于索引超出范围的Python 3问题
我有这个问题。当我运行这段代码时,上面的文件会给我一个索引超出范围的错误Python 3.x 关于索引超出范围的Python 3问题,python-3.x,Python 3.x,我有这个问题。当我运行这段代码时,上面的文件会给我一个索引超出范围的错误 f = open(sys.argv[1], 'r') file_contents = [x.split('\t')[2:5] for x in f.readlines()] #Set the variables for average and total for cities total = 0 city = set() for line in file_contents: print(line[0]) 这是
f = open(sys.argv[1], 'r')
file_contents = [x.split('\t')[2:5] for x in f.readlines()]
#Set the variables for average and total for cities
total = 0
city = set()
for line in file_contents:
print(line[0])
这是文件的内容
2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex
2012-01-01 09:00 Fort Worth Women's Clothing 153.57 Visa
2012-01-01 09:00 San Diego Music 66.08 Cash
2012-01-01 09:00 Pittsburgh Pet Supplies 493.51 Discover
2012-01-01 09:00 Omaha Children's Clothing 235.63 MasterCard
读取文件后需要关闭该文件,建议使用
with
语句打开该文件,该语句会自动关闭该文件
with open(sys.argv[1], 'r') as f:
file_contents = [x.split(' ')[2:5] for x in f.readlines()]
#Set the variables for average and total for cities
total = 0
city = set()
for line in file_contents:
print(line[0])
但是,您遇到的问题是将行拆分为\t
,请使用空格,这样可以满足您的需要
输出
您是否尝试过打印(行)?上述代码无法解决问题。它仍然存在与
列表索引超出范围相同的错误
您的问题在于切片[2:5]
以及如何分割数据。例如,如果删除[2:5]
,您将看到整个文件的打印没有任何问题。或者,像我一样,如果按物理空间分割数据,可以保留切片,因为数据被正确分割。我将其分割为[2:5]
是因为我想打印项目类别、价格和付款方式。无论您的意图如何,这仍然是失败的原因。您需要更改分割文件中每一行的方式,或者更改文件本身以使用不同的分隔符。上面的代码对我来说没有问题,而您的代码给了我列表索引超出范围的错误
09:00
09:00
09:00
09:00
09:00