内部for循环不在python中执行

时间:2018-01-18 01:53:20

标签: python python-3.x

我有input.csv,如下所示

apple 400  
banana 401  
mango 430  
orange 440  
banana 401  
orange 440  
mango 430  
apple 400  
orange 440  
banana 401

我想输出像output.csv

apple 400  2  
banana 401 3  
mango 430 2   
orange 440 3 

即我们应该计算该特定类型的项目数,并将计数作为第3列插入

我尝试过以下代码

with open('new.csv','r') as csvinput:
  with open('update.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput)
    reader = csv.reader(csvinput)

    all = []
    row = next(reader)
    row.append("No.of.Rows")
    all.append(row)

    cn = Counter(map(itemgetter(0), reader))
    for k, v in cn.items():
        print("k compared is::",k)
        for row in reader:
           print("Executing inner loop")
           print("row value compared is ::",row[0])
           if k == row[0] :
             print("matched")
             # here i want to write the count v to the 3rd column

在上面的代码中,for for循环没有被执行。

你能进一步帮我吗

2 个答案:

答案 0 :(得分:0)

感谢您的输入,我修改了下面的代码

for k, v in cn.items():
         print("k compared is::",k)
         with open('new.csv','r') as csvinput:
              reader = csv.reader(csvinput)
              for row in reader:
                  print("Executing inner loop")
                  print("row value compared is ::",row[0])
                  if k == row[0] :
                     print("matched")
                     row.append(v)
                     all.append(row)
                     break
writer.writerows(all)

使用此代码它可以工作,但我担心csv文件将被打开并读取k次,所以有没有更好的解决方案

答案 1 :(得分:0)

我认为以下代码可以正常工作

import csv
from collections import Counter
from operator import itemgetter
with open('new.csv','r') as csvinput:
    reader = csv.reader(csvinput)
    cn = Counter()
    for row in reader:
        trow=tuple(row)
        cn[trow] += 1
    print cn
with open('update.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput)
    for row in cn:
        writer.writerow([row[0],row[1],cn[row]])