Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在迭代之外使用计数器,忽略列表中的空行_Python_List_Iteration_Counter - Fatal编程技术网

Python 在迭代之外使用计数器,忽略列表中的空行

Python 在迭代之外使用计数器,忽略列表中的空行,python,list,iteration,counter,Python,List,Iteration,Counter,我正在寻找一种在循环外使用计数器的方法。在本例中,我们的想法是打印列表中的行数,忽略空行。到目前为止,我认为我用错了计数器,因为它还没有计算空行数 import csv with open('data.csv', 'rb') as f: reader2 = csv.reader(f) reader2.next() linecount = len(zip(*reader2)[0]) f.seek(0) reader = csv.reader(f) r

我正在寻找一种在循环外使用计数器的方法。在本例中,我们的想法是打印列表中的行数,忽略空行。到目前为止,我认为我用错了计数器,因为它还没有计算空行数

import csv
with open('data.csv', 'rb') as f:
    reader2 = csv.reader(f)
    reader2.next()
    linecount = len(zip(*reader2)[0])
    f.seek(0)
    reader = csv.reader(f)
    reader.next()
    counter = []
    print(linecount)
    print(type(str(counter)))
    for row in reader:
    if not row[0]: #avoid empty lines
        counter += 1
            continue
    print row
    print (int(linecount)-len(counter))

如果你只想计算行数,为什么你还要用CSV呢?您所需要的只是以下简单内容:

with open('/tmp/uni.py','r') as f:
    empty = 0
    nonempty = 1
    for line in f:
        if line.strip():
            nonempty +=1
        else :
            empty +=1

print empty, nonempty

这可以用更少的代码行来完成,但为了清晰起见,我这样做了。

如果您只想计算行数,为什么还要使用CSV?您所需要的只是以下简单内容:

with open('/tmp/uni.py','r') as f:
    empty = 0
    nonempty = 1
    for line in f:
        if line.strip():
            nonempty +=1
        else :
            empty +=1

print empty, nonempty

这可以用更少的代码行来完成,但为了清晰起见,我这样做了。

计数器是什么?列表还是整数?请您也检查一下缩进,好吗?计数器应该是整数。我得到的错误消息是
TypeError:“int”对象不可编辑
如果
计数器
应该是一个整数,为什么要执行
计数器=[]
len(计数器)
?由于
linecount
是一个整数,因此执行
int(linecount)
没有意义。只需从
counter=0开始,不要在末尾使用
len()
,就这么简单?英雄联盟我应该在计数器
的作用是什么之前得到它?列表还是整数?请您也检查一下缩进,好吗?计数器应该是整数。我得到的错误消息是
TypeError:“int”对象不可编辑
如果
计数器
应该是一个整数,为什么要执行
计数器=[]
len(计数器)
?由于
linecount
是一个整数,因此执行
int(linecount)
没有意义。只需从
counter=0开始,不要在末尾使用
len()
,就这么简单?英雄联盟我早该拿到的