我希望有人指出我正确的方向。从我的阅读中,我相信使用字典最适合这种需求,但是我绝不是一名熟练的程序员,我希望有人可以给我一些帮助。这是我拥有的CSV文件:
11362672,091914,100914,100.00,ITEM,11,N,U08
12093169,092214,101514,25.00,ITEM,11,N,U10
12162432,091214,101214,175.00,ITEM,11,N,U07
11362672,091914,100914,65.00,ITEM,11,N,U08
11362672,091914,100914,230.00,ITEM,11,N,U08
我想将第一列作为键,然后将第二列作为该键的值,以便:
这是我想要获得的输出:
1,11362672,091914,100914,100.00,ITEM,11,N,U08 # occurrence 1 for key: 11362672
2,11362672,091914,100914,65.00,ITEM,11,N,U08 # occurrence 2 for key: 11362672
3,11362672,091914,100914,230.00,ITEM,11,N,U08 # occurrence 3 for key: 11362672
1,12093169,092214,101514,25.00,ITEM,11,N,U10 # occurrence 1 for key: 12093169
1,12162432,091214,101214,175.00,ITEM,11,N,U07 # occurrence 1 for key: 12162432
我需要保持每一行的完整性,这就是为什么我认为词典效果最好的原因。我没有很多,但这就是我开始的目的。这是我需要帮助进行排序,计数和附加计数器的地方。
import csv
with open('C:/Download/item_report1.csv', 'rb') as infile:
reader = csv.reader(infile)
dict1 = {row[0]:row[1:7] for row in reader}
print dict1
给我:
{
'11362672': ['091914', '100914', '230.00', 'ITEM', '11', 'N'],
'12093169': ['092214', '101514', '25.00', 'ITEM', '11', 'N'],
'12162432': ['091214', '101214', '175.00', 'ITEM', '11', 'N']
}
简要地说,您应该使用计数器来计算键值,并使用列表来存储行。
在您读取csv时,请跟踪您看到键值的次数,并在您读取键值时将其插入每行的开头。
读入文件后,可以首先按键值对其进行排序,然后按出现次数对它进行排序。
import csv
counter = {}
data = []
with open('report.csv','rb') as infile:
for row in csv.reader(infile):
key = row[0]
if key not in counter:
counter[key] = 1
else:
counter[key] += 1
row.insert(0,counter[key])
data.append(row)
for row in sorted(data,key=lambda x: (x[1],x[0])):
print row
这又是同一回事,写的略有不同,按照官方的风格指南有4个空格,而不是我个人偏爱的两个。
import csv
# key function for sorting later
def second_and_first(x):
return (x[1],x[0])
# dictionary to store key_fields and their counts
counter = {}
# list to store rows from the csv file
data = []
with open('report.csv','rb') as infile:
for row in csv.reader(infile):
# For convenience, assign the value of row[0] to key_field
key_field = row[0]
# if key_field is not in the dictionary counter. Add it with a value of 1
if key_field not in counter:
counter[key_field] = 1
# otherwise, it is there, increment the value by one.
else:
counter[key_field] += 1
# insert the value associated with key_field in the counter into the start of
# the row
row.insert(0,counter[key_field])
# Append the row to
data.append(row)
for row in sorted(data,key=second_and_first):
print row
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句