finding a longest list within the lists in python

2020-04-14 16:26发布

问题:

I'm just a new in python and I need to print the lists which has minimum and maximum items in a list.

For example if i have:

 total_list = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]

I need to return a list with a minimum and maximum length of itself. How can I do it simply in python way?

I try to iterate over it but all I could receive is the only len of each item in a list

Output must be:

total_list[0] and total_list[2]

Thanks in advance

回答1:

max and min function in python accepts a key argument that will find the max of an iterable based on what defined as a key. so, try this:

max(total_list, key=len)

then you can use total_list.index to find those indexes



回答2:

total_list = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]

print('total_list[{0}] and total_list[{1}]'.format(total_list.index(min(total_list, key=len)), total_list.index(max(total_list, key=len))))

OUTPUT:

C:\Users\Desktop>py x.py
total_list[0] and total_list[2]


回答3:

The usage of min( iterable, key=len) (min/max) is easiest. If you like to go through your list yourself, you can do this like so:

tl  = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]

# init shortest and longest to 1st element of list
# use a tuple to store:  ( listdata, length, position in original list )
shortest = longest = (tl[0], len(tl[0]), 0)

# iterate over remaining elements
for pos_act,act in enumerate(tl[1:],1): # start enumerate on 1 to fix position due slicing
    # get actual length
    len_act = len(act)

    # is it larger then current largest?
    if len_act > longest[1]:
        longest = (act,len_act, pos_act)

    # is it shorter then current shortest?
    if len_act < shortest[1]:
        shortest = (act, len_act, pos_act)

print ("Shortest: {} with len {} on position {}".format(*shortest))
print ("Longest: {} with len {} on position {}".format(*longest))

Output:

Shortest: [1, 2, 3] with len 3 on position 0
Longest: [1, 2, 3, 4, 5] with len 5 on position 2

Doku:

  • enumerate(iterable[,start_value])