从列表中返回半唯一值 [英] Returning semi-unique values from a list

查看:106
本文介绍了从列表中返回半唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道怎么说这个,但是说​​我有一个包含以下序列的列表:

Not sure how else to word this, but say I have a list containing the following sequence:

[a,a,a,b,b,b,a,a,a]

我想退货:

[a,b,a]

原则上如何做到这一点?

How would one do this in principle?

推荐答案

你可以使用 itertools.groupby ,它将同一组中的连续相同元素分组并返回键值对的迭代器,其中键是您要查找的唯一元素:

You can use itertools.groupby, this groups consecutive same elements in the same group and return an iterator of key value pairs where the key is the unique element you are looking for:

from itertools import groupby  

[k for k, _ in groupby(lst)]
# ['a', 'b', 'a']







lst = ['a','a','a','b','b','b','a','a','a']

这篇关于从列表中返回半唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆