2017-10-16 64 views
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]但它没有返回。任何人都可以帮助我的代码?谢谢

+0

请注意,您为读取的每一行重设'curr_arr'('curr_arr = []') – math2001

回答

0

您的value目前是一个字符串。你应该强制转换为int所以用数组中的项,其是整数可以True匹配的项目比较:

value = int(sys.argv[1]) 

否则,if curr_arr[n] == val: ...总是False,和found_indices列表保持为空。

此外,您可以使用enumerate更加优雅地构建列表,以便在列表理解的项目旁边生成索引。

found_indices = [i for i, x in curr_arr if x == value]