我有一个这样的列表清单:[[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
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
“S IN a
。如果有就做a = filter(a, None)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句