我希望有人能给我指出正确的方向。从我读过的内容来看,我相信使用字典最适合这种需要,但我绝不是一个高级程序员,我希望有人能提供一些帮助并帮助我。这是我的 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
关于python 将 csv 文件读取为字典并排序和递增计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25999514/