2013-04-23 41 views
0

它正在变得非常接近我做我想做的,这是让用户通过索引号(0-11)选择列表中的项目。Python:通过索引选择,打印列项目

当我输入一个数字,即5时,它会打印出“You selected [5] as origin point" .. great!但我希望它显示图的名称,而不是索引号,名称在第2列(如果索引列计为0)。我意识到这要求整数,但我希望它很容易固定。

另一个问题是,如果我输入18,其打印"You selected [18]...",但没有18

def fmp_sel(): 
    DataPlotLoc= file('MonPlotDb.csv', 'rU') 
    fmpList = csv.reader(DataPlotLoc, dialect=csv.excel_tab) 
    next(fmpList, None) 
    for item in enumerate(fmpList): 
     print "[%d] %s" % (item) 

    while True: 
     try: 
      in_Sel = raw_input(('''Choose a plot from list, or 'q' to quit: ''')) 

      if in_Sel == 'q': 
       print 'Quit?' 
       conf = raw_input('Really? (y or n)...') 
       if conf == 'y': 
        print 'Seeya!' 
        break 
       else: 
        continue 

      in_Sel = DataPlotLoc[int(in_Sel) + 1] # The +1 is to align to correct index 
      print 'You selected', in_Sel, 'as origin point' 
      break 

     except (ValueError, IndexError): 
      print 'Error: Try again' 
+0

不清楚你在问什么!考虑重写问题以获得更多答案并更详细地描述您已有的内容:什么是DataPlotLoc? – pwagner 2013-04-23 06:40:15

+0

你在哪里调用'fmp_sel()'?另外,您可能需要'yield'而不是'next',并且可能最接近您所遇到的问题:您将'DataPlotLoc'索引为文件对象,而不是'fmpList'或'fmp_sel'的结果它是一个发电机。 – Evert 2013-04-23 06:43:15

+0

'DataPlotLoc'是一个'file'对象,你不能用'[int(in_Sel)+ 1]'索引它。 'fmpList'是一个'csv.reader'对象,不是一个列表。要将“MonPlotDb.csv”文件的所有行读入到可以索引的内存中,请在'next(fmpList,None)'行之后尝试'fmpList = [DataPlotLoc中的行的行]'。 – martineau 2013-04-23 09:02:40

回答

0

您需要将fmpList添加到列表中,csv阅读器只会循环一次,

也可以将代码更改为

DataPlotLoc= file('MonPlotDb.csv', 'rU') 
fmpList = list(csv.reader(DataPlotLoc, dialect=csv.excel_tab)) 
for item in enumerate(fmpList): 
    print "[%d] %s" % (item) 
if fmpList: 
    while True: 
     try: 
      in_Sel = raw_input(('''Choose a plot from list, or 'q' to quit: ''')) 
      in_Sel = DataPlotLoc[int(in_Sel)][1] # The +1 is to align to correct index 
      print 'You selected', in_Sel, 'as origin point' 
      break  
     except (ValueError, IndexError): 
      print 'Error: Try again'