python - 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!
解决方案
使用对内部列表进行切片的列表推导。
result = [l[:N] for l in original_list]
推荐阅读
- python - 在 Dataframe 中为分类数据添加标签
- ios - iOS 应用测试本地化翻译是否具有相同的键
- python - 如何在 python 中抓取完整的 Instagram 页面?
- python - 如何让 python 信任我服务器的 TLS 自签名证书:ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败
- html - 为什么元素不在一行中?
- hibernate - 本机插入后如何获取新记录ID
- javascript - 如何在 Bing Maps JavaScript V8 中动态设置语言
- php - PDO 查询将 SQL 列拆分为字符数组
- javascript - 如何从AngularJS中的一个服务响应调用其他服务?
- javascript - 如何轻松关闭弹出窗口?