Python删除列表中的重复项,1 == 1.0 True [英] Python removing duplicates in list and 1==1.0 True

查看:190
本文介绍了Python删除列表中的重复项,1 == 1.0 True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除列表中的重复值,但是如果不在...中,则使用 set() code> loop我只得到部分正确的决定。
例如对于 ['asd','dsa',1,'1',1.0]

I need to remove duplicates values in a list, but with set() or for ... if not in... loop I only get partially correct decisions. For example for ['asd', 'dsa', 1, '1', 1.0]

我得到:

['asd', 'dsa', 1, '1']

但所需的结果是:

['asd', 'dsa', 1, '1', 1.0]

我可以实现吗?

推荐答案

您可以尝试

In [3]: [value for _, value in frozenset((type(x), x) for x in l)]
Out[3]: [1.0, '1', 1, 'dsa', 'asd']

我们创建一个(临时) frozenset 包含元素及其类型的元组 - 保持相等的元素(例如 1 1.0 True ),但具有不同的类型。然后我们遍历它,解包元组并检索元素( value )。

We create a (temporary) frozenset of tuples containing both element and its type - to keep elements that are equal (such as 1, 1.0 and True) but have different types. Then we iterate over it, unpack tuples and retrieve elements (value).

当然,我们也可以使用普通的 set ,这是可变的,但是我们不需要可变性,因为我们的集合是暂时的。

Sure, we could as well use ordinary set, which is mutable, but we don't need mutability because our set is temporary.

请注意,这不一定保留原始订单。

Note that this won't necessarily preserve the original order.

如果您需要保留原始订单,请使用 collections.OrderedDict ,这是一个哈希映射(就像常规 dict ),因此与 frozenset / 设置

If you need the original order preserved, use collections.OrderedDict, which is a hash map (just like regular dict) and therefore works similarly to frozenset/set

In [16]: from collections import OrderedDict

In [17]: [value for _, value in OrderedDict.fromkeys((type(x), x) for x in l)]
Out[17]: ['asd', 'dsa', 1, '1', 1.0]

这篇关于Python删除列表中的重复项,1 == 1.0 True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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