Python - get the last element of each list in a list of lists

前端 未结 5 2032
时光取名叫无心
时光取名叫无心 2021-01-12 06:20

My question is quite simple, I have a list of lists :

my_list = [[\'a1\',\'b1\'],[\'a2\',\'b2\'],[\'a3\',\'b3\',\'c3\'],[\'a4\',\'b4\',\'c4\',\'d4\',\'e4\']]         


        
相关标签:
5条回答
  • 2021-01-12 06:59

    You can try:

    my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]
    print(my_list)
    
    for each_list in my_list:
        last_element = each_list[-1]
        print(last_element)
    

    Code tested successfully to arrive at the expected result - In the Attachment

    0 讨论(0)
  • 2021-01-12 07:00

    You can try ,

    Here is demo.

    >>> [i.pop() for i in my_list]
    ['b1', 'b2', 'c3', 'e4']
    

    OR

    >>> my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]
    >>> [i[-1] for i in my_list]
    ['b1', 'b2', 'c3', 'e4']
    
    0 讨论(0)
  • 2021-01-12 07:10

    See the below answer,

    my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]
    
    new_list = []
    for sub_list in my_list:
        new_list.append(sub_list[-1])
    
    print(new_list) # o/p: [ 'b1' , 'b2' , 'c3' , 'e4' ]
    

    I hope it helps you to find the answer.

    0 讨论(0)
  • 2021-01-12 07:12

    An alternative with map:

    last_items = map(lambda x: x[-1], my_list)
    

    or:

    from operator import itemgetter
    print map(itemgetter(-1), my_list)
    
    0 讨论(0)
  • 2021-01-12 07:13

    You can get the last element of each element with the index -1 and just do it for all the sub lists.

    print [item[-1] for item in my_list]
    # ['b1', 'b2', 'c3', 'e4']
    

    If you are looking for idiomatic way, then you can do

    import operator
    get_last_item = operator.itemgetter(-1)
    print map(get_last_item, my_list)
    # ['b1', 'b2', 'c3', 'e4']
    print [get_last_item(sub_list) for sub_list in my_list]
    # ['b1', 'b2', 'c3', 'e4']
    

    If you are using Python 3.x, then you can do this also

    print([last for *_, last in my_list])
    # ['b1', 'b2', 'c3', 'e4']
    
    0 讨论(0)
提交回复
热议问题