简体   繁体   English

为什么此代码会产生列表列表?

[英]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: fruit.csv的内容是:

apple,orange,kiwi,tomato

The value of fruitList is a list of lists: fruitList的值是一个列表列表:

[['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. 阅读器从CSV文件生成 See the documentation : 请参阅文档

Each row read from the csv file is returned as a list of strings. 从csv文件读取的每一行都作为字符串列表返回。

It doesn't matter here that your file only consists of 1 row; 您的文件只包含1行,这并不重要; list(reader) produces a list of all the rows, be that 0, 1 or 20 million. list(reader)生成所有行的列表,可以是0、1或2000万。 So a file with just 1 row gives you a list containing that single row as a list. 因此,只有1行的文件会为您提供一个包含该单行作为列表的列表。

If you only ever expect one row, iterate one step with the next() function : 如果您只希望获得一行,请使用next()函数迭代一个步骤:

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. next(reader, [])告诉函数,如果reader根本不产生任何东西,则返回一个空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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