python计算前9行的第3列中有多少个1?

python计算前9行的第3列中有多少个1?,python,csv,count,Python,Csv,Count,假设我们有这个csv a,0.900,1,1 b,0.895,1,2 c,0.893,1,3 d,0.881,1,4 e,0.879,1,5 f,0.875,1,6 g,0.875,0,7 h,0.875,0,8 i,0.869,0,9 j,0.865,1,10 k,0.862,1,11 是否有任何有效且正确的方法来计算前9行第3列中有多少个1 这是我的错误代码: current_file="column3.csv" file=open(current_file,'r') a_count=

假设我们有这个csv

a,0.900,1,1
b,0.895,1,2
c,0.893,1,3
d,0.881,1,4
e,0.879,1,5
f,0.875,1,6
g,0.875,0,7
h,0.875,0,8
i,0.869,0,9
j,0.865,1,10
k,0.862,1,11
是否有任何有效且正确的方法来计算前9行第3列中有多少个1

这是我的错误代码:

current_file="column3.csv"

file=open(current_file,'r')

a_count=[];

count = 0

for line in csv.reader(file):

        while (count <= n-1):

            a_count.append(int(line[2]));   

            count=count+1

a=sum(a_count)                                  

print a_count

print a
期望输出:

a_count=[1, 1, 1, 1, 1, 1, 0, 0, 0]

a=6

您可以使用以下代码来获得所需的输出

import csv


n=9
file=open("filename",'r')
a_count = []
count = 0

for line in csv.reader(file):
    print line[1]
    if(line[2]=="1"):
        a_count.append(int(line[2]));
    else:
        a_count.append(0);
    count=count+1
    if(count==9):
        break

a=sum(a_count)                                  
print a_count
print a
输出:

       [1, 1, 1, 1, 1, 1, 0, 0, 0 ]
        6
试试这个:

import csv

with open('column3.csv') as f:
   reader = csv.reader(f)
   rows = list(reader)

print(sum(int(i[2]) for i in rows[:9]))

您也可以尝试下面的代码

>>> with open('file.csv') as f:
    l = []
    count = int(0)
    for line in csv.reader(f):
        l.append(int(line[2]))
    m = l[:9]
    for i in m:
        if i==1:
            count=count+1
    print(m)
    print(count)


[1, 1, 1, 1, 1, 1, 0, 0, 0]
6

谢谢!它起作用了。两个答案都不错。我不知道该投谁的票。请选择一个容易理解的答案:-)
>>> with open('file.csv') as f:
    l = []
    count = int(0)
    for line in csv.reader(f):
        l.append(int(line[2]))
    m = l[:9]
    for i in m:
        if i==1:
            count=count+1
    print(m)
    print(count)


[1, 1, 1, 1, 1, 1, 0, 0, 0]
6