Python - 获取列表列表中每个列表的最后一个元素 [英] Python - get the last element of each list in a list of lists

查看:59
本文介绍了Python - 获取列表列表中每个列表的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,我有一个列表列表:

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

如何轻松获得每个列表的最后一个元素,即:

  ['b1','b2','c3','e4'] 

谢谢!

解决方案

您可以获取索引为 -1 的每个元素的最后一个元素,并对所有子列表执行此操作.

>

 打印[my_list中项目的[item [-1]]# ['b1', 'b2', 'c3', 'e4'] 

如果您正在寻找惯用的方法,那么可以

  import运算符get_last_item = operator.itemgetter(-1)打印地图(get_last_item,my_list)#['b1','b2','c3','e4']打印[get_last_item(sub_list)为my_list中的sub_list]#['b1','b2','c3','e4'] 

如果您使用的是Python 3.x,那么您也可以这样做

  print([*的最后一个,my_list的最后一个])#['b1','b2','c3','e4'] 

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']]

How can I get easily the the last element of each list i.e. :

[ 'b1' , 'b2' , 'c3' , 'e4' ]

Thanks !

解决方案

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']

这篇关于Python - 获取列表列表中每个列表的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆