python-3.x 如何沿着单列嵌套列表中获取唯一值?

ruarlubt  于 2023-02-06  发布在  Python
关注(0)|答案(1)|浏览(118)

我需要提取唯一的子列表的基础上,从嵌套列表的第一个元素。

in = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = [['a','b'], ['e','f'], ['g','h']]

我的方法是将两个列表分成两个列表,并分别检查元素。

lis = [['a','b'], ['a','d'], ['e','f'], ['g','h']]
lisa = []
lisb = []
for i in lis:
    if i[0] not in lisa:
        lisa.append(i[0])
        lisb.append(i[1])
out = []
for i in range(len(lisa)):
    temp = [lisa[i],lisb[i]]
    out.append(temp)

当处理包含10,00,000+个子列表的列表时,这是一个开销很大的操作。有没有更好的方法?

33qvvth1

33qvvth11#

使用内存效率高的生成器函数和辅助set对象来过滤第一个唯一子元素上的项(取第一个唯一):

def gen_take_first(s):
    seen = set()
    for sub_l in s:
        if sub_l[0] not in seen:
            seen.add(sub_l[0])
            yield sub_l

inp = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = list(gen_take_first(inp))
print(out)
[['a', 'b'], ['e', 'f'], ['g', 'h']]

相关问题