2013-04-23 40 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'