a = [1,2,2,3,3,4,5,6]
1、第一种方法
def get_unique_N(iterable, N):
"""Yields (in order) the first N unique elements of iterable.
Might yield less if data too short."""
seen = set()
for e in iterable:
if e in seen:
continue
seen.add(e)
yield e
if len(seen) == N:
return
k = get_unique_N([1,2,2,3,3,4,5,6], 4)
print(list(k))
输出结果:
[1,2,3,4]
2、第二种方法
文档:itertools unique_everseen recipe:
a = [1,2,2,3,3,4,5,6]
def unique_everseen_limit(iterable, limit=5):
seen = set()
seen_add = seen.add
for element in iterable:
if element not in seen:
seen_add(element)
yield element
if len(seen) == limit:
break
res = list(unique_everseen_limit(a)) # [1, 2, 3, 4, 5]
print(res)
3、第三种方法
a = [1,2,2,3,3,4,5,6]
from itertools import islice
def unique_everseen(iterable):
seen = set()
seen_add = seen.add
for element in iterable:
if element not in seen:
seen_add(element)
yield element
res = list(islice(unique_everseen(a), 5)) # [1, 2, 3, 4, 5]
print(res)
4、第四种方法
unique_everseen
配方可通过more_itertools.unique_everseen或在第三方库中使用toolz.unique,因此可以使用:
a = [1,2,2,3,3,4,5,6]
from itertools import islice
from more_itertools import unique_everseen
from toolz import unique
res = list(islice(unique_everseen(a), 5)) # [1, 2, 3, 4, 5]
res = list(islice(unique(a), 5)) # [1, 2, 3, 4, 5]
print(res)