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

2024-10-02 12:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文

它已经非常接近于我想要的,即让用户通过索引号(0-11)在列表中选择一个项目。在

当我输入一个数字,即5,它打印“^ {CD1>}…太好了!但我希望它能显示出地块的名称,而不是索引号。名称在第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'

Tags: orcsvtoin名称youinputraw
1条回答
网友
1楼 · 发布于 2024-10-02 12:34:32

你需要列出一个列表,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'

相关问题 更多 >

    热门问题