我有这样一个列表:[[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]。
我想编写一个将返回的函数:[16, 14, 12, 7, 6]:即列表列表中的最后5个元素。
这是我所拥有的代码,但它一点也不像奏鸣曲(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发布于 2015-02-19 05:51:17
import itertools as it
a = [[1, 2], [4, 5, 6], [], [7, 12, 14, 16]]
reversed(it.islice(it.chain.from_iterable(reversed(a)), 5))这实际上是假设a中没有a,如果有do a = filter(a, None)的话。
发布于 2015-02-19 05:45:36
考虑到您的例子,我将假设您的列表中的项是可迭代的或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]发布于 2015-02-19 05:53:01
您可以使用列表理解:
>>> 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的solution)
https://stackoverflow.com/questions/28599370
复制相似问题