-1

I would like to put the max number(s) to a new array, I've tried every thing that I can think of and none seem to work....(adding to an empty result array, concat, etc)

Obviously the for loop is printing the max function out with the proper numbers, but I have a weak understanding of return vs print and how to capture values from a loop , etc.

list = [[21, 34, 345, 2], [555, 22, 6, 7], [94, 777, 65, 1], [23, 54, 12, 666]]
for i in list:
    print max(i)

345
555
777
666
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • `for .... : code_to_add_i_to_array`, basically., instead of `for ...: print i`. – Marc B Oct 22 '15 at 17:08
  • It would be more conventional to convert your list to an array first and then take the max() of the array. 1) turn the nested list to a single, 2) convert the single list to array, 3 take max() /argmax in Numpy – user1749431 Oct 22 '15 at 17:09

5 Answers5

5

Just apply max to every sublist:

Python 2:   map(max, lists)
Python 3:   list(map(max, lists))

Of course the latter only works if you don't shadow the built-in list function with your variable (which is a bad idea anyway, so I used the name lists instead).

>>> lists = [[21, 34, 345, 2], [555, 22, 6, 7], [94, 777, 65, 1], [23, 54, 12, 666]]
>>> map(max, lists)
[345, 555, 777, 666]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
2
newArray = [max(i) for i in list]

search up List Comprehension, one of the most useful things about python.

R Nar
  • 5,465
  • 1
  • 16
  • 32
  • Yes, I was checking out list comprehensions a bit yesterday....and may have even tried to hack something out with it to make this work, but no dice – Richard Stiehm Oct 22 '15 at 17:13
0

Try a list comprehension:

L = [[21, 34, 345, 2], [555, 22, 6, 7], [94, 777, 65, 1], [23, 54, 12, 666]]
maxes = [max(sublist) for sublist in L]
print(maxes)
# [345, 555, 777, 666]
jakevdp
  • 77,104
  • 11
  • 125
  • 160
0

Wow, folks are harsh today. I think that I understood your question;

new_list = [max(i) for i in list]
for k in new_list:
     print (k)
SteveJ
  • 3,034
  • 2
  • 27
  • 47
0

Working Example in Python 2 — Tested with Python 2.6.9 and 2.7.10

L01 = [[21, 34, 345, 2], [555, 22, 6, 7], [94, 777, 65, 1], [23, 54, 12, 666]]
L02 = map(max, L01)
print(L02)

Output

[345, 555, 777, 666]


Working Example in Python 3 — Tested with Python 3.2.5 and 3.4.3 and 3.5.0

The only difference is that map() is wrapped by list().

L01 = [[21, 34, 345, 2], [555, 22, 6, 7], [94, 777, 65, 1], [23, 54, 12, 666]]
L02 = list(map(max, L01))
print(L02)

Output

[345, 555, 777, 666]
jesterjunk
  • 2,342
  • 22
  • 18