在使用 Python 的集差时保留顺序 [英] Retaining order while using Python's set difference

查看:64
本文介绍了在使用 Python 的集差时保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 做一个集差操作:

x = [1, 5, 3, 4]y = [3]结果 = 列表(设置(x) - 设置(y))打印(结果)

我得到:

[1, 4, 5]

如您所见,列表元素的顺序已更改.如何以原始格式保留列表 x?

解决方案

看起来您需要一个有序集而不是常规集.

<预><代码>>>>x = [1, 5, 3, 4]>>>y = [3]>>>打印(列表(OrderedSet(x)-OrderedSet(y)))[1, 5, 4]

Python 没有有序集合,但很容易实现:

导入集合类 OrderedSet(collections.Set):def __init__(self, iterable=()):self.d = collections.OrderedDict.fromkeys(iterable)def __len__(self):返回 len(self.d)def __contains__(self, element):self.d 中的返回元素def __iter__(self):返回迭代器(self.d)

希望这有帮助:-)

I'm doing a set difference operation in Python:

x = [1, 5, 3, 4]
y = [3]

result = list(set(x) - set(y))
print(result)

I'm getting:

[1, 4, 5]

As you can see, the order of the list elements has changed. How can I retain the list x in original format?

解决方案

It looks like you need an ordered set instead of a regular set.

>>> x = [1, 5, 3, 4]
>>> y = [3]
>>> print(list(OrderedSet(x) - OrderedSet(y)))
[1, 5, 4]

Python doesn't come with an ordered set, but it is easy to make one:

import collections

class OrderedSet(collections.Set):
    def __init__(self, iterable=()):
        self.d = collections.OrderedDict.fromkeys(iterable)

    def __len__(self):
        return len(self.d)

    def __contains__(self, element):
        return element in self.d

    def __iter__(self):
        return iter(self.d)

Hope this helps :-)

这篇关于在使用 Python 的集差时保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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