Issue
I have a text file that looks like this:
12345
23451
11221
21219
11223
71231
I want to have an array of lengths (number_of_columns - 1
) that will store the maximum values of each column respectively except for the last column.
So my output array for this above example will look something like: 7 3 4 5
I don't want to use pandas here. I am unable to understand how to proceed.
Solution
Use:
with open(datafile) as infile:
# convert each line to an iterable of ints
rows = (map(int, line.strip()) for line in infile)
# find the maximum per col, exclude the last one
*res, _ = (max(col) for col in zip(*rows))
print(res)
Output
[7, 3, 4, 5]
As an alternative:
with open(datafile) as infile:
# convert each line to an iterable of ints exclude the last one
rows = (map(int, line.strip()[:-1]) for line in infile)
# find the maximum per col,
res = [max(col) for col in zip(*rows)]
print(res)
Answered By - Dani Mesejo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.