Retaining order while using Python#39;s set difference(在使用 Python 的设置差异时保留顺序)
本文介绍了在使用 Python 的设置差异时保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 Python 中进行集差操作:
I'm doing a set difference operation in Python:
x = [1, 5, 3, 4]
y = [3]
result = list(set(x) - set(y))
print(result)
我明白了:
[1, 4, 5]
如您所见,列表元素的顺序发生了变化.如何以原始格式保留列表 x?
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 没有有序集,但很容易制作:
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 的设置差异时保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在使用 Python 的设置差异时保留顺序
基础教程推荐
猜你喜欢
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
