Read csv, then enumerate

随声附和 提交于 2020-01-13 10:55:08

问题


At the moment, I have a list directly in my code and am using enumerate so I can use the list index numbers for the user to select one of the items. Looks like this (just header row included)

fmpList = [['Date', 'ID', 'Plot No', 'Modified', 'Lat', 'Long']......
for item in enumerate(fmpList[]):            
    print "[%d] %s" % item

This works well but I don't want to put the list in the function but rather to read the csv from file. The alternative I used to do this is...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

This also works but I can't seem to combine the 2... read the csv file in, then enumerate to be able to have a selection based on index. Help would be greatly appreciated

EDIT: So now I've got working code as I wanted...

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
        next (csvfile, None)
        plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
        for row in enumerate (plotlist):
            print '[%s]' %(item[2])

But the last line is not giving me column 2 only displayed. In fact, I'm after column 0 (the index no) and 2 (the plot name). [0] gives the first column...cool, but any number greater than 1 gives IndexError: ..out of range. Tried every combo but nothing works


回答1:


enumerate(...) works on any iterable

import csv
with open ('fmpList.csv', 'rU') as csvfile: 
    next(csvfile, None) # skip header
    plotlist = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for i, row in enumerate(plotlist):
        print "[%d] %s" % (i, row)


来源:https://stackoverflow.com/questions/16139558/read-csv-then-enumerate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!