Home > Software design >  Find max values using "for loop" when I have to separate lists
Find max values using "for loop" when I have to separate lists

Time:10-28

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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]
  • Related