栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用于在Python中删除重复项的Iterator对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用于在Python中删除重复项的Iterator对象

更好地创建一个生成器函数,像这样

>>> def unique_values(iterable):...     seen = set()...     for item in iterable:...         if item not in seen:...  seen.add(item)...  yield item...

然后您可以创建一个唯一值的元组,像这样

>>> tuple(unique_values((1, 2, 3, 3, 4, 4, 5)))(1, 2, 3, 4, 5)

如果您确定将始终对数据进行排序,则可以避免创建数据集并仅跟踪先前的数据,就像这样

>>> def unique_values(iterable):...     it = iter(iterable)...     previous = next(it)...     yield previous...     for item in it:...         if item != previous:...  previous = item...  yield item>>> tuple(unique_values((1, 2, 3, 3, 4, 4, 5)))(1, 2, 3, 4, 5)

您可以像这样编写一个带有类的迭代器对象

>>> class Unique:...     def __init__(self, iterable):...         self.__it = iter(iterable)...         self.__seen = set()... ...     def __iter__(self):...         return self... ...     def __next__(self):...         while True:...  next_item = next(self.__it)...  if next_item not in self.__seen:...      self.__seen.add(next_item)...      return next_item... >>> for item in Unique((1, 2, 3, 3, 4, 4, 5)):...     print(item)... 12345

您可以参考此答案,以及Python
3数据模型文档中的
“迭代器类型”部分。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号