Finding The Largest Number in a Nested List in Python

后端 未结 5 1490
我在风中等你
我在风中等你 2021-01-17 07:11

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)

相关标签:
5条回答
  • 2021-01-17 07:15

    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)
    
    0 讨论(0)
  • 2021-01-17 07:17

    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]
    
    0 讨论(0)
  • 2021-01-17 07:23

    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]
    
    0 讨论(0)
  • 2021-01-17 07:27
    newArray = [max(i) for i in list]
    

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

    0 讨论(0)
  • 2021-01-17 07:34

    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]
    
    0 讨论(0)
提交回复
热议问题