简体   繁体   English

Python - 确定循环的第一次迭代

[英]Python - Determine first iteration of loop

I hae some code that reads in a file, skips the first line and then field splits every line.我有一些读入文件的代码,跳过第一行,然后字段拆分每一行。 On the first pass (ie - the first line) I want to record the length of field split to a variable.在第一遍(即第一行)中,我想将字段拆分的长度记录到一个变量中。 I know I can do it like this with a counter variable but is there a cleaner way?我知道我可以使用计数器变量来做到这一点,但有没有更清洁的方法?

line_count=1
for line in line_split[1:]:
        field_split = line.split(b'\t')
        if line_count=1:
            number_of_fields=len(field_split)
        line_count=line_count+1 

You can replace defining the line_count with an enumerator:您可以用枚举器替换定义line_count

for line_count, line in enumerate(line_split[1:]):
    field_split = line.split(b'\t')
    if line_count == 0:
        number_of_fields=len(field_split)
number_of_fields=len(line_split[1].split(b'\t')) if len(line_split) > 1

for index, line in enumerate(line_split[1:]):
   # Do whatever with index and line

This is optimal because it evaluates if only once.这是最优的, if它只评估一次。 And by using enumerate on list you can get both index and item of the list.通过在列表上使用enumerate ,您可以获得列表的索引和项目。

for line_count, line in enumerate(line_split[1:], 1):
    field_split = line.split(b'\t')
        if line_count == 1:
            number_of_fields = len(field_split)

If you only want to detect the first line, you could do it like this -如果你只想检测第一行,你可以这样做 -

first_line = True
for line in line_split[1:]:
    field_split = line.split(b'\t')
    if first_line:
        number_of_fields = len(field_split)
        first_line = False
        continue

The 'continue' will skip the rest of the block and move to the next line immediately. “继续”将跳过该块的 rest 并立即移至下一行。

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

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