简体   繁体   English

使用 itertools 的 for 循环来计算行数

[英]For loops with itertools to count rows

I have a .csv document with 16 rows.我有一个 .csv 文件,有 16 行。 Each row starts with letters, in this case with a or b .每行以字母开头,在本例中为ab

The outer for loop will check, line by line, the first letter.外部 for 循环将逐行检查第一个字母。 If row x starts with b , the second for-loop will count all rows until b occurs again.如果行xb开头,则第二个 for 循环将计算所有行,直到b再次出现。

Example:例子:

1. a
2. a
3. a
4. a
5. b
6. a
7. a
8. a
9. a
10.a
11.a
12.a
13.b
14.a
…

b is found in line 5, next in row 13. There are 7 rows between… b位于第 5 行,接下来是第 13 行。之间有 7 行……

That's my script to count rows from line 5 to line 13:这是我计算第 5 行到第 13 行行的脚本:

"Verschachtelteitertools" "Verschachtelteitertools"

import itertools
import re  
df = open('zeilen.csv')

for i, line in enumerate(df):
    #print(i,line)
    if re.search('b',line):
        #print(i,line)
        k = i+1
        count = 1
        #print(k)
        for line in itertools.islice(df,k):

            if bool(re.search('b',line)) == False:
                count=count+1
        lineX = count

print(lineX)

I have chosen itertools.islice() to count rows between b (1st occurrence) and b in line 13. k should represent the starting Point of the inner loop.我选择了itertools.islice()来计算第 13 行中b (第一次出现)和b的行k应该代表内部循环的起点。

import itertools import re
df = open('zeilen.csv') for i, line in enumerate(df): #print(i,line) if re.search('b',line): #print(i,line) k = i+1 count = 1 #print(k) for line in itertools.islice(df,k):
if bool(re.search('b',line)) == False: count=count+1 lineX = count print(lineX)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM