This is my first time asking for help here, but surely not last since I'm just a struggling beginner.
I have a text file with some numbers eg. :
5 26 83 1 5645
7 3758 69 4 84
I want to sort these lines into lists, which I have partially done with this line of code: result = [line.split(" ") for line in file.readlines()]
- not sure if this is the right way to do it in order to work with it but maybe I'll find some help here
Now, when I have every line of the text file separated as a list of values, I want to find the highest value in the whole text file and find in which line the number is. - I can find the highest value with "max" method but that's about it
For example, out of 20 lines of numbers, the highest value is "94515" and is located in 13th row.
That's what I would like to accomplish.
Try this:
with open('path/to/file', 'r') as file:
result = [list(map(int, line.split())) for line in file.readlines() if line.strip()]
max_int = max(j for i in result for j in i)
line_nums = [i+1 for i, j in enumerate(result) if max_int in j]
Processing line by line:
with open('data.txt', 'r') as file:
imax, max_line = float('-inf'), -1 # init of overall max and line number
for line_no, line in enumerate(file):
# Use try/except to ignore problem lines (such as blank line)
try:
line_max = max(map(int, line.rstrip().split())) # max in line
# Line above does the following:
# line.strip() remove "/n" at end of line
# .split() convert string into list of numbers
# (e.g. "1 2 3".split() -> ['1', '2', '3']
# map(int, lst) converts list of strings into numbers
# (i.e. ['1', '2', '3'] -> [1, 2, 3]
# max takes the max of the numbers in the list
if line_max > imax:
imax, max_line = line_max, line_no # update overall max
except:
continue # ignores problems (such as blank lines)
print(f'Max {imax} on line {max_line}')
Test
data.txt file contents (blank third line)
5 26 83 1 5645
7 3758 69 4 84
17 8 19 21 15
232 231 99999 15
Output (outputs max value and line number)
Max 99999 on line 4
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.