简体   繁体   中英

How can I print the index corresponding to the selected value in a for loop

I want to be able to print the index of the maximum value found during my for loop.

I am able to find the maximum value but not the corresponding index. It always gives me the last line index as output.

    with open(fname) as infile:
        largest = None
        index = 0
        lines = infile.readlines()[19:]
        for line in lines:  
            line.replace("\n", '') 
            case = line.split()
            test = float(case[3])
            if largest is None or test > largest:
            largest = test
            index += 1
     print(largest, index)

It's because you aren't keeping track of the largest index anywhere.

with open(fname) as fh:
    largest, index = 0, 0 # start both of these at 0 so you don't have to check against None
    for i in range(19):
        next(fh) # consume up to the 19th line

    # use enumerate to track the line numbers, avoiding the need for 
    # manually incrementing a counter
    for i, line in enumerate(fh):
        line = line.strip().split() # strip will take off trailing newlines
        test = float(line[3])
        if test > largest:
            # track both values here
            largest, index = test, i

print(largest, index)

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