抱歉,我相信這是一個常見問題,但似乎無法找到所需結果的確切答案。我只想返回基于一個元素的列表列表中的唯一項目。例子;List = [[1,2],[2,3],[1,4],[1,5],[6,3]]期望的結果;List = [[2,3],[6,3]]由于 1 作為多個列表項中的第一個元素存在,因此我希望忽略所有這些項。有沒有一種簡單的方法可以做到這一點?
1 回答

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
它可能很誘人,list.count但如果天真地使用它,它會使使用它的解決方案變得 O(n^2)。
O(n) 解決方案將使用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]]
添加回答
舉報
0/150
提交
取消