在Python中将.csv值作为单个列表导入 [英] Importing .csv values as single list in Python

查看:41
本文介绍了在Python中将.csv值作为单个列表导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 csv 文件,该文件具有一列如下所示的记录:

I have a csv file that has one column of records that looks like this:

test1
test2
test3
...

我使用以下命令将它们导入到Python列表中:

I imported them into a Python list using this:

import csv

results = []
with open('test.csv', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

print(results)

效果很好,但是,它像这样打印出来:

That worked fine, however, it prints them out like this:

[['test1'],['test2'],['test3']]

我将如何调整代码以使其打印在单个列表中,而不是像这样:

How would I adjust my code to have them print out in a single list instead like this:

['test1','test2','test3']

,一个输出是否比另一个输出更受青睐?我意识到这取决于用例.我很好奇其他人如何通过.csv处理导入的列表,以及一个人相对于另一个有什么优势.

and, is one output more preferred than the other? I realize it is use-case dependent. I am just curious how others work with imported lists via .csv, and what advantage one would have over the other.

谢谢!

推荐答案

尝试以下代码

import csv

results = []
with open('test.csv', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row[0])

print(results)

这篇关于在Python中将.csv值作为单个列表导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆