简体   繁体   English

如何“减少”列表中的重复

[英]How to 'reduce' repetitions in a list

I am having trouble thinking of the most efficient way to reduce repetitions in a list. 我很难想到减少列表中重复的最有效方法。

a = ['x','x','x','y','y','y','z','z','z','x','x','x','z','z','z','z','z','z']

The desired output (if I reduce sets of 3) would be: 所需的输出(如果我减少3套)将是:

a_reduced = ['x','y','z','x','z','z']

I was thinking of looping through each element and do a '[i] and [i+1] and [i+2] condition' thing, but I am sure there is a super easy and efficient way to achieve this and that I am just missing something. 我当时想遍历每个元素并执行“ [i],[i + 1]和[i + 2]条件”,但是我敢肯定,有一种超级简单有效的方法可以实现这一目标,只是缺少一些东西。 Assist please, thanks! 请协助,谢谢!

If your repetitions are always in sets of 3 you could simply do: 如果您的重复次数始终为3组,则可以执行以下操作:

a = ['x','x','x','y','y','y','z','z','z','x','x','x','z','z','z','z','z','z']
a_reduced = a[::3]
print a_reduced
>>>['x', 'y', 'z', 'x', 'z', 'z']

This will just grab every 3rd element from the list. 这只会从列表中获取每个第3个元素。 Again, this is assuming your list is always in sets of 3. It will be skewed if they are not. 再次,这是假设您的列表始终以3组为一组。如果不是,则将倾斜。 Otherwise you if you just want to condense all of the unique repetitions as they go you can use itertools.groupby which will do just that: 否则,如果您只想压缩所有唯一重复,则可以使用itertools.groupby来完成:

from itertools import groupby
a = ['x','x','x','y','y','y','z','z','z','x','x','x','z','z','z','z','z','z']
a_reduced = [item[0] for item in groupby(a)]
print a_reduced
>>>['x', 'y', 'z', 'x', 'z']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM