[英]Python - get the last element of each list in a list of lists
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 ie :我怎样才能轻松获得每个列表的最后一个元素,即:
[ '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.您可以获取索引为-1
的每个元素的最后一个元素,并对所有子列表执行此操作。
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如果您使用的是 Python 3.x,那么您也可以这样做
print([last for *_, last in my_list])
# ['b1', 'b2', 'c3', 'e4']
An alternative with map
: map
的替代方案:
last_items = map(lambda x: x[-1], my_list)
or:或者:
from operator import itemgetter
print map(itemgetter(-1), my_list)
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代码测试成功以达到预期结果 - 在附件中
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.我希望它能帮助你找到答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.