我不知道为什么我一直收到错误"字符串索引超出范围"第47行print_data的另一个错误(数据。有人可以解释一下原因吗?谢谢
def open_file():
user_input = input('Enter a file name: ')
try:
file = open(user_input, 'r')
return file
except FileNotFoundError:
return open_file()
def read_data(file):
counter = [0 for _ in range(9)]
for line in file.readlines():
num = line.strip()
if num.isdigit():
i = 0
digit = int(num[i])
while digit == 0 and i < len(num):
i += 1
digit = int(num[i])
if digit != 0:
counter[digit - 1] += 1
return counter
def print_data(data):
benford = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 4.1, 4.6]
header_str = "{:5s} {:7s}{:8s}"
data_str = "{:d}:{:6.1f}% ({:4.1f}%)"
total_count = sum(data)
print(header_str.format("Digit", "Percent", "Benford"))
for index, count in enumerate(data):
digit = index + 1
percent = 100 * count / total_count
print(data_str.format(digit, percent, benford[index]))
def main():
file = open_file()
data = read_data(file)
print_data(data)
file.close()
if __name__ == "__main__":
main()
这是我给出的确切错误
Traceback (most recent call last):
File "./lab08.py", line 52, in <module>
main()
File "./lab08.py", line 47, in main
data = read_data(file)
File "./lab08.py", line 26, in read_data
digit = int(num[i])
答案 0 :(得分:2)
我认为错误源于此:
while digit == 0 and i < len(num):
i += 1
digit = int(num[i])
如果你交换后两行,你将正确索引,即:
while digit == 0 and i < len(num):
digit = int(num[i])
i += 1
例如,如果您的字符串num
的长度为10,则最后一个元素位于索引9(从0开始索引)。对于该循环的第一次迭代,您将具有数字num[1]
,对于第十次迭代,您将具有num[10]
。
另一种方法是使用这样的列表理解:
for n in num:
if digit != 0:
break
digit = int(n)