python获取列表列表中的最后5个元素

时间:2015-02-19 05:42:59

标签: python list list-comprehension

我有一个列表如下:[[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]

我想写一个将返回的函数:[16, 14, 12, 7, 6]:即列表列表中的最后5个元素。

这是我的代码,但它根本不是pythonic(master_list包含上面的列表):

    def find_last_five():
        last_five = []
        limit = 5

        for sublist in reversed(master_list):
            # have to check that list is not None.
            if sublist:
                for elem in sublist:
                    last_five.append(elem)
                    limit -= 1
                    if (limit == 0):
                         return last_five

        return last_five

7 个答案:

答案 0 :(得分:4)

举个例子;我会假设您列表中的项目是可迭代的或None;

>>> import itertools

>>> lst = [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]
>>> print list(itertools.chain(*[l for l in lst if l is not None]))[-5:]
[6, 7, 12, 14, 16]

答案 1 :(得分:4)

import itertools as it

a = [[1, 2], [4, 5, 6], [], [7, 12, 14, 16]]
reversed(it.islice(it.chain.from_iterable(reversed(a)), 5))

实际上假设None中没有a。如果只有a = filter(a, None)

答案 2 :(得分:4)

您可以使用列表理解:

>>> tgt=[[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]
>>> [e for sub in tgt if sub for e in sub][-5:]
[6, 7, 12, 14, 16]

过滤掉None。过滤掉其他非列表或元组:

>>> [e for sub in tgt if isinstance(sub, (list, tuple)) for e in sub][-5:]

如果你想要的东西不必先整理整个列表列表,你可以直接处理结构,然后向上移动直到你有你想要的东西:

result=[]
current=[]
it=reversed(tgt)
while len(result)<5:
    if current:
        result.append(current.pop())
        continue
    else:
        try: 
             current=next(it)
        except StopIteration:
            break

(或使用John 1024&#39; s solution

答案 3 :(得分:3)

不使用外部模块:

master = [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]
new = []
total = 5

for x in reversed(master):
    if x:
        new += list(reversed(x))[:total-len(new)]
        if total == len(new):
            break

print(new)

这会产生:

[16, 14, 12, 7, 6]

这是所需的列表,其中包含所需顺序的元素。

答案 4 :(得分:0)

使用flatten食谱的替代方法:

import collections

l = [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]    

def flatten(l):

    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            for sub in flatten(el):
                yield sub
        else:
            yield el


print([v for v in flatten(l) if v][-5:])     
# gives: [6, 7, 12, 14, 16]

答案 5 :(得分:0)

另一种方法怎么样?

a = [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]
sum(filter(None, a), [])[-1:-6:-1]

只有因为列表中的filter类型,才需要None函数。如果它只是一个列表列表,这样写起来会简单得多:

sum(a, [])[-1:-6:-1]

这背后的原理?我们实际上使用&#39; +&#39;列表的运算符只是继续将列表添加到单个列表中。请注意,对于较长的列表,这不是选择(如果您选择;))的方法。对于较小和中等列表,这很好。

答案 6 :(得分:-1)

我会使用itertools来执行此操作。像

这样的东西
list(itertools.chain.from_iterable(x for x in l if x is not None))[:-5]

其中l是您的输入列表。

相关问题