简体   繁体   中英

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:

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. And by using enumerate on list you can get both index and item of the list.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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