Martin
Martin

Reputation: 1

Find max values using "for loop" when I have to separate lists

I have the following lists and would like to get the maximum values for each person and create a new list using exclusively the for loop and max function. How can I do it?

persons = ['John', 'James', 'Robert']
values = [
    (101, 97, 79),
    (67, 85, 103),
    (48, 201, 105),
]

I'm looking for this ouput:

Output 1 = [('John', 101), ('James', 103), ('Robert', 201]
Output 2 = [101, 103, 201]

Can anyone help?

I just do not manage to get this result at all.

Upvotes: 0

Views: 213

Answers (4)

MartinsM
MartinsM

Reputation: 110

output1 = [(i, max(j)) for i,j in zip(persons, values)]
output2 = [max(x) for x in values]

Upvotes: 0

The Thonnu
The Thonnu

Reputation: 3624

Loop through the items of persons and values with zip:

a = [(p, max(v)) for p, v in zip(persons, values)]
b = [max(v) for v in values]

print(a) # [('John', 101), ('James', 103), ('Robert', 201]
print(b) # [101, 103, 201]

Upvotes: 0

KillerRebooted
KillerRebooted

Reputation: 659

persons = ['John', 'James', 'Robert']
values = [  (101, 97, 79), 

            (67, 85, 103),

            (48, 201, 105),      

         ]

output_1 = []
output_2 = []

for i, j in zip(persons, values):
    output_1.append( (i, max(j)) )
    output_2.append(max(j))

print(output_1)
print(output_2)

Upvotes: 0

Rodrigo Guzman
Rodrigo Guzman

Reputation: 487

for i, j in zip(persons, values):
    print(i,max(j))

Upvotes: 2

Related Questions