如何使用列表推导删除列表中的相邻重复元素? [英] How to remove adjacent duplicate elements in a list using list comprehensions?

查看:78
本文介绍了如何使用列表推导删除列表中的相邻重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用python中的列表推导从列表中过滤相邻重复项?

Is there a way to use list comprehensions in python to filter adjacent duplicates from a list?

这是我的意思的示例:

>>> xs = [1,2,2,3]
>>> print added.reAdj(xs)
[1,2,3]

通过SE搜索发现早期查询询问了相似,但问题略有不同:是否可以从列表中删除所有重复项,但不明确要求涉及列表理解的解决方案.使用列表推导式的动机特别遵循

A search through SE revealed an earlier inquiry asking a similar but slightly different question: whether all duplicates could be removed from a list, but not explicitly asking for solutions involving list comprehensions. The motivation for using list comprehensions specifically follows a recognition of their advantages over traditional for loops. Users suggested the use of the set() function or standard looping as such:

result = []
most_recent_elem = None
for e in xs:
    if e != most_recent_elem:
        result.append(e)
        most_recent_elem = e

set()建议不能满足要求,因为删除了不相邻的重复项,而循环有效但很冗长.

The set() suggestion fails to meet the task in that non-adjacent duplicates are removed, while the loop is effective but verbose.

似乎需要一种安全地引用列表理解中的下一个元素的方法,如下所示.

It seems a means for safely referencing the next element in a list comprehension as follows is needed.

[x for x in xs if x != **x.next()**]

有什么想法吗?

推荐答案

您可以使用 列表理解 枚举 @AChampion建议的解决方案:

You could use list comprehension and enumerate with solution suggested by @AChampion:

xs = [1,2,2,2,1,1]
In [115]: [n for i, n in enumerate(xs) if i==0 or n != xs[i-1]]
Out[115]: [1, 2, 1]

该列表理解返回项(如果是第一个)或后面的项(如果它不等于前一个).由于 if 语句的懒惰求值,它可以工作.

That list comprehension return item if it's first or for the following if it's not equal to previous. It'll work due to lazy evaluations of if statement.

这篇关于如何使用列表推导删除列表中的相邻重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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