如何在 python 中从 csv 文件创建数组



我有一个csv文件,其中包含这样的列表:

票价:12、1233、234

元12、

1233、989

12, 9898, 213

票价:14、1233、987

票价:14、1233、876

我想为相似的行创建一个数组。 例如,在上面的例子中,我想创建一个数组,如下所示: 12, 1233 [234, 989] 因为它们前两行中的值相同

import csv with open('check.csv', 'r') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',') for row in reader:
         print(re.search( #uniqueSet = list(set(x)) 

此代码将为您完成大部分工作

#read the csv file
with open('csv_file.csv','r') as f:
   lines=[l.split(',') for l in f.readlines()]
#Aggregate by the 3rd field by the first two fields
import collections    
d=collections.defaultdict(list)
for l in lines:
   d[(l[0],l[1])].append(l[2])

csv(csv_file.csv)文件将被读取为字典(变量d),您剩下的就是将其转换为列表或您想要的任何格式

最新更新