0
我在查找输入文件中的值的所有索引。程序将接受要搜索的数字作为第一个命令行参数,输入文件的名称作为第二个参数。我无法输出指数在该值从下面的代码中发现:如何从输入文件输出值的所有索引
import sys
value = sys.argv[1]
file_name = sys.argv[2]
file = open(file_name, 'r')
print('The value of file \"{}\" to be searched:\n{}'.format(file_name, value))
for line in file.readlines():
curr_arr = []
for i in line.split(','):
curr_arr +=[int(i)]
def find_values(curr_arr, val):
found_indexes = []
sum = 0
for n in range(len(curr_arr)):
sum += curr_arr[n]
if curr_arr[n] == val:
found_indexes += [n]
sum = sum + 1
return found_indexes
print 'The index(s) of the occurrence of {} in {}: {}'.format(value, curr_arr, find_values(curr_arr, value))
而这就是我得到:
a1.py 7 text.csv
The value of file "text.csv" to be searched:
7
The index(s) of the occurrence of 7 in [2, 3, 7, 9, 7, 3, 2]:
我应该得到[2, 4]但它没有返回。任何人都可以帮助我的代码?谢谢
请注意,您为读取的每一行重设'curr_arr'('curr_arr = []') – math2001