我希望按子列表
中的唯一项目筛选列表示例:
# ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
我正在使用,想要:
def setx0(arr):
r = []
filter(lambda x : r.append(x) if x[0] not in set(map(lambda x: x[0], r)) else False, arr)
return r
更好的方式?
答案 0 :(得分:1)
假设列表已经排序,您可以使用itertools.groupby
:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = [[1, 0], [1, 1], [2, 2]]
>>> [next(g) for k, g in groupby(lst, itemgetter(0))]
[[1, 0], [2, 2]]
答案 1 :(得分:1)
我会直接前进:
lst = [[1, 0], [1, 1], [2, 2]]
seen = set()
new_list = []
for ele in lst:
if ele[0] not in seen:
new_list.append(ele)
seen.add(ele[0])
print new_list
结果:
[[1, 0], [2, 2]]
答案 2 :(得分:0)
不是非常有效,但如果你喜欢单行:
try:
reduce
except NameError: # Python 3
from functools import reduce
lst = [[1, 0], [1, 1], [2, 2]]
filtered = reduce(lambda a, b: a+[b] if b[0] not in set(x[0] for x in a) else a,
lst, [])
print(filtered) # -> [[1, 0], [2, 2]]
答案 3 :(得分:0)
With sorted list, the easiest would be
>>> lst = [[1, 0], [1, 1], [2, 2]]
>>> dict(reversed(lst)).items()
[(1, 0), (2, 2)]
答案 4 :(得分:0)
试试这个
const lst = [[1, 0], [1, 1], [2, 2]],
foundItems = [],
result = []
for (let i in lst) {
const lstItem = lst[i]
if (foundItems.indexOf(lstItem[0]) === -1) {
foundItems.push(lstItem[0])
result.push(lstItem)
}
}
console.log(JSON.stringify(result)) // print [[1, 0], [2, 2]]