从列表中删除元素 [英] Removing elements from a list of a list

查看:206
本文介绍了从列表中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的数据,这是一个列表的列表。我想删除每个列表中的最后两个元素,只留下前三个元素。我已经尝试 list.append() list.pop()但似乎无法让他们工作。我想这是不可能的从一个列表中删除元素的for循环,这是我以前一直在尝试。什么是最好的方式去这个?

I have the data below, which is a list of lists. I would like to remove the last two elements from each list, leaving only the first three elements. I have tried list.append(), list.pop() but can't seem to get them to work. I guess it is not possible to remove elements from a list in a for loop, which is what I had been previously trying. What is the best way to go about this?

data = [(datetime.datetime(2013, 11, 12, 19, 24, 50), u'78:E4:00:0C:50:DF', u' 8', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 50), u'78:E4:00:0C:50:DF', u' 8', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 48), u'9C:2A:70:69:81:42', u' 5', u'Hon Hai Precision In 12:', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'00:1E:4C:03:C0:66', u' 9', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'20:C9:D0:C6:8F:15', u' 8', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:5D:43:90:C8:0B', u' 11', u'Intel Orate', u' MADEGOODS'), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:96:7B:C1:76:90', u' 15', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:96:7B:C1:76:90', u' 15', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'04:F7:E4:A0:E1:F8', u' 32', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'04:F7:E4:A0:E1:F8', u' 32', u'Apple', u'')]


推荐答案

您可以使用列表理解并创建

You could use a list comprehension and create a new list of lists with 2 elements removed from each sublist

data = [x[:-2] for x in data]

这篇关于从列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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