csv列出并分析python

时间:2018-02-04 00:16:22

标签: python list csv count

我正在从csv文件中读取一些值,并使用以下代码将这些值转换为列表。 csv文件只是一行,大约有2000个值,它们是“1”或“0”。使用代码,我试图计算csv文件中有多少“1”。

def countX(a, x):
    count = 0
    for ele in a:
        if (ele == x):
            count = count + 1
    return count

def countX(a, x):
    return a.count(x)

with open(my_file_name, 'r') as in1file:
    mylist = [row[0] for row in csv.reader(in1file, delimiter=';')]

print (mylist)

a = [mylist]
x = 1

countX 
print(countX(a, x))

我遇到的问题是“我的列表”会返回类似

的内容
['0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0'] 

因此,当我查询我的列表以计算“1”的计数时,由于某种原因,我总是得到值0。如果我只是创建一个列表并制作

a = [1,1,1,1,1,1,0,0] 

我将得到一个6的计数值。我怎样才能完成这项工作,以便从我的csv文件中获得1的数量?

5 个答案:

答案 0 :(得分:0)

尝试在代码中将delimiter命名参数更改为,

所以读取CSV的代码是:

with open(my_file_name, 'r') as in1file:
    mylist = csv.reader(in1file, delimiter=',')

答案 1 :(得分:0)

您的列表现在只包含一个字符串。您需要获取字符串并在其上执行split(','),这将为您提供单字符字符串列表,然后您可以将它们转换为整数,我认为这就是您想要的。

如果这真的是你的mylist,而且长度为1,那么我的想法就是:

>>> mylist = ['0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0'] 
>>> mylist[0]
'0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0'
>>> [int(item) for item in mylist[0].split(',')]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

如果mylist有很多类似的字符串,你可以这样做:

lines = []
for line in mylist:
    lines.append([int(item) for item in line.split(',')])

答案 2 :(得分:0)

以下是适合您案例的快速代码段:

MyList = ['0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0']
MyList_Split = MyList[0].split(',')
print(MyList_Split.count('1'))
# Returns 2

答案 3 :(得分:0)

def countX(a, x):
count = 0
for ele in a:
    if (ele == x):
        count = count + 1
return count

def countX(a, x):
return a.count(x)

with open(my_file_name, 'r') as in1file:
mylist = [row[0] for row in csv.reader(in1file, delimiter=';')]

new_list = [int(item) for item in mylist[0].split(',')]

a = [new_list]
x = 1

countX 
print(countX(a, x))

答案 4 :(得分:0)

>>> from collections import Counter
>>> MyList = ['0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0']
>>> counts = Counter(MyList[0].split(','))
>>> counts
Counter({'0': 18, '1': 2})
>>> counts['1']
2