Returning semi-unique values from a list

蓝咒 提交于 2019-12-11 02:08:36

问题


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]

and I would like to return:

[a,b,a]

How would one do this in principle?


回答1:


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']



回答2:


Psidoms way is a lot better, but I may as well write this so you can see how it'd be possible just using basic loops and statements. It's always good to figure out what steps you'd need to take for any problem, as it usually makes coding the simple things a bit easier :)

original = ['a','a','a','b','b','b','a','a','a']
new = [original[0]]

for letter in original[1:]:
    if letter != new[-1]:
        new.append(letter)

Basically it will append a letter if the previous letter is something different.




回答3:


Using list comprehension:

original = ['a','a','a','b','b','b','a','a','a']
packed = [original[i] for i in range(len(original)) if i == 0 or original[i] != original[i-1]]
print(packed)  # > ['a', 'b', 'a']

Similarly (thanks to pylang) you can use enumerate instead of range:

[ x for i,x in enumerate(original) if i == 0 or x != original[i-1] ]



回答4:


more_itertools has an implementation of the unique_justseen recipe from itertools:

import more_itertools as mit

list(mit.unique_justseen(["a","a","a","b","b","b","a","a","a"]))
# ['a', 'b', 'a']


来源:https://stackoverflow.com/questions/41497600/returning-semi-unique-values-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!