【问题标题】:How do i make a sublist of every CSV row and put that sublist inside a list如何制作每个 CSV 行的子列表并将该子列表放入列表中
【发布时间】:2019-08-23 22:07:06
【问题描述】:

我正在为 csv 文件中的每一行创建一个子列表,但我得到了一个列表

wines_list = []

for row in wines:
    wines_list.append(row)

print(wines_list)

这会返回:

['id', 'country', 'description', 'designation', 'points', 'price', 
'province', 'taster_name', 'title', 'variety', 'winery', 'fixed acidity', 
'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free 
sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 
'alcohol']

但我不想将所有值附加到子列表,并将其附加到 wines_list

所以我希望 wines_list 变成这样:

[[1, 'netherlands', 'description of the wine', 'designation', 'points', 'price', 
'province', 'taster_name', 'title', 'variety', 'winery', 'fixed acidity', 
'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free 
sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 
'alcohol'], ANOTHER SUB LIST HERE]

【问题讨论】:

标签: python pandas list csv sublist


【解决方案1】:

最简单的方法是这样的

import csv
pathtocsv='path/to/file'
with open(pathtocsv,'r') as cfile:
    creader=csv.reader(cfile,delimiter=',')
    wines_list=list(creader)

print(wines_list)

那么wines_list 将是一个列表列表

【讨论】:

  • 如果您不想要标题,当然可以。或 wines_list.pop(0)with 块的末尾
  • 谢谢!让它工作,我会尽快接受!
猜你喜欢
  • 1970-01-01
  • 2019-07-20
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 2021-10-31
  • 2019-02-25
相关资源
最近更新 更多