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.
CodePudding user response:
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)
CodePudding user response:
[max(lst) for lst in zip(*[map(int,line) for line in data.split() if line])][:-1]
CodePudding user response:
There are many ways to do this. Here's just one of them:
with open('foo.txt') as infile:
a = []
for line in infile:
for i, d in enumerate(line[:-2]):
if len(a) < i 1:
a.append([])
a[i].append(int(d))
print(*map(max,a))