gpt4 book ai didi

python - 读取 CSV 文件中的所有列?

转载 作者:行者123 更新时间:2023-11-30 22:49:36 25 4
gpt4 key购买 nike

我正在尝试读取 CSV 文件,然后获取每列中的所有值并将其放入单独的列表中。我不想要按行的值。由于 CSV 读取器只允许循环浏览文件一次,因此我使用eek() 方法返回到开头并读取下一列。除了使用 Dict 映射之外,还有更好的方法吗?

infile = open(fpath, "r")
reader = csv.reader(infile)

NOUNS = [col[0] for col in reader]
infile.seek(0) # <-- set the iterator to beginning of the input file

VERBS = [col[1] for col in reader]
infile.seek(0)
ADJECTIVES = [col[2] for col in reader]
infile.seek(0)
SENTENCES = [col[3] for col in reader]

最佳答案

像这样的事情可以一次性完成:

kinds = NOUNS, VERBS, ADJECTIVES, SENTENCES = [], [], [], []
with open(fpath, "r") as infile:
for cols in csv.reader(infile):
for i, kind in enumerate(kinds):
kind.append(cols[i])

关于python - 读取 CSV 文件中的所有列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com