Python:按索引选择,打印列项

时间:2013-04-23 06:11:21

标签: python indexing

它正在接近我想做的事情,这让用户通过它的索引号(0-11)选择列表中的项目。

当我输入一个数字即5时,它会打印“You selected [5] as origin point" ..很棒!但我希望它显示图表的名称,而不是索引编号。名称在第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'

1 个答案:

答案 0 :(得分:0)

你需要fpm列表到列表,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'