有人可以帮我设置一个柜台吗?我读过你可以使用Counter
来显示任何值的计数。但我想在行迭代时打印计数。
这是我的文件示例:
A12000,NAME
A12000,NAME
A12000,NAME
A13000,NAME
A14000,NAME
A15000,NAME
我想打印:
1,A12000,NAME
2,A12000,NAME
3,A12000,NAME
1,A13000,NAME
1,A14000,NAME
1,A15000,NAME
这就是我所拥有的:
import csv
from collections import Counter
with open('O:/csvdocs/count1.csv', 'rb') as cf:
rr = csv.reader(cf)
for row in rr:
acctnum = []
acctnum.append(row[0])
acctcounter = Counter(acctnum)
print acctcounter
这就是打印:
Counter({'A12000': 1})
Counter({'A12000': 1})
Counter({'A12000': 1})
Counter({'A13000': 1})
Counter({'A14000': 1})
Counter({'A15000': 1})
谢谢
答案 0 :(得分:0)
您想为所有行创建一个 Counter
和一个 list
,例如:
with open('O:/csvdocs/count1.csv', 'rb') as cf:
rr = csv.reader(cf)
acctnum = [] # outside loop
for row in rr:
acctnum.append(row[0])
acctcounter = Counter(acctnum) # also outside loop
print acctcounter
答案 1 :(得分:0)
from collections import Counter
with open('O:/csvdocs/count1.csv', 'rb') as cf:
count = Counter(cf.readlines())
with open("file.csv",'wb') as w:
[[w.write("{},{}".format(i,key)) for i in range(1,count[key]+1)] for key in count]