首页 > 解决方案 > Select top n elements from list of lists in Python

问题描述

I'm trying to create a new list of lists from an existing one. I'm trying to select top N values from the inner lists and output a new list of lists. The current list looks like this:

[[('with', -3.608809242675524),
  ('cruz', -3.6553518286125546),
  ('rt', -2.962847001582534)],
[ ('his', -2.9577717646107025),
  ('is', -2.9627189839205403),
  ('to', -2.968666793195209)]]

Now I want to take this as an input and output the top 1 element from each list. The real list is longer and has more than 2 lists, and I would want to take top N elements. The output should look like this:

[[('with', -3.608809242675524)],
[('his', -2.9577717646107025)]]

Any help would be appreciated!

标签: pythonpython-3.xlistloopsnested-lists

解决方案


使用对内部列表进行切片的列表推导。

result = [l[:N] for l in original_list]

推荐阅读