简体   繁体   中英

Why Does This Code Produce a List of Lists?

I have a function:

def csvToList( filename ):
    with open(filename, 'r') as fp:
        reader = csv.reader(fp)
        myList = list(reader)
    return myList

and call it with:

fruitList = csvToList('fruit.csv')

The contents of fruit.csv is:

apple,orange,kiwi,tomato

The value of fruitList is a list of lists:

[['apple', 'orange', 'kiwi', 'tomato']]

Why does this code produce a list of lists and not just a simple "flat" list, like this:

['apple', 'orange', 'kiwi', 'tomato']

The reader produces rows from a CSV file. See the documentation :

Each row read from the csv file is returned as a list of strings.

It doesn't matter here that your file only consists of 1 row; list(reader) produces a list of all the rows, be that 0, 1 or 20 million. So a file with just 1 row gives you a list containing that single row as a list.

If you only ever expect one row, iterate one step with the next() function :

def csvToList( filename ):
    with open(filename, 'r') as fp:
        reader = csv.reader(fp)
        return next(reader, [])

next(reader, []) tells the function to return an empty list if reader doesn't produce anything at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM