简体   繁体   中英

Removing elements from a list of a list

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

您可以使用列表推导并创建一个新的列表列表,并从每个子列表中删除2个元素

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

As @christian says, you have a list of tuple , as opposed to list . The distinction is significant here as tuple is immutable. You can convert to list of list like this

data = map(list, data)

Now you can mutate each item as you iterate over it

for item in data:
     del item[-2:]

In your case the list comprehension is better because it works on your list of tuple equally well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM