从基于第一个元素的列表列表中仅返回唯一的事件 [英] Returning only unique occurrences from a list of lists based on the first element

查看:42
本文介绍了从基于第一个元素的列表列表中仅返回唯一的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我认为这是一个常见问题,但似乎无法找到所需结果的确切答案.

Apologies, I believe this is a common question, but cannot seem to find an exact answer for the desired outcome.

我只想返回基于一个元素的列表列表中的唯一项.

I would like to return ONLY the unique items in a list of lists based on one element.

示例;

List = [[1,2],[2,3],[1,4],[1,5],[6,3]]

期望的结果;

List = [[2,3],[6,3]]

由于 1 作为多个列表项中的第一个元素存在,我希望它们都被忽略.

As 1 exists as the first element in several list items, I would like all of them disregarded.

有没有简单的方法可以做到这一点?

Is there a simple way to do this?

推荐答案

使用 list.count 可能很诱人,但如果天真地使用它会使解决方案使用 O(n^2).

It may be tempting to use list.count but it will make the solution using it O(n^2) if used naively.

O(n) 解决方案将使用 collections.Counter:

An O(n) solution would be using collections.Counter:

from collections import Counter

nested_list = [[1,2],[2,3],[1,4],[1,5],[6,3]]

counter_map = Counter(sublist[0] for sublist  in nested_list)
print(counter_map)
output = [sublist for sublist in nested_list if counter_map[sublist[0]] == 1]
print(output)

输出

Counter({1: 3, 2: 1, 6: 1})
[[2, 3], [6, 3]]

这篇关于从基于第一个元素的列表列表中仅返回唯一的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆