我需要提取唯一的子列表的基础上,从嵌套列表的第一个元素。
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+个子列表的列表时,这是一个开销很大的操作。有没有更好的方法?
1条答案
按热度按时间33qvvth11#
使用内存效率高的生成器函数和辅助
set
对象来过滤第一个唯一子元素上的项(取第一个唯一):