python消除序列的重复值并保持顺序不变的实例

作者:EricRae 时间:2023-03-13 14:53:49 

python 消除序列的重复值,并保持原来顺序

1、如果仅仅消除重复元素,可以简单的构造一个集合


$ python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1 , 3, 5, 1, 8, 1, 5]
>>> set(a)
{8, 1, 3, 5}
>>>

2、利用集合或者生成器解决:值必须是hashable类型


$ python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def dupe(items):
... seen = set()
... for item in items:
... if item not in seen:
... yield item
... seen.add(item)
...
>>> a = [1 , 3, 5, 1, 8, 1, 5]
>>> list(dupe(a))
[1, 3, 5, 8]
>>>

3、消除元素不可哈希:如字典类型


Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def rem(items, key=None):
... seen = set()
... for item in items:
... va = item if key is None else key(item)
... if va not in seen:
... yield item
... seen.add(va)
...
>>> a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]>>> list(rem(a, key=lambda d: (d['x'],d['y'])))
[{'y': 2, 'x': 1}, {'y': 3, 'x': 1}, {'y': 4, 'x': 2}]
>>> list(rem(a, key=lambda d: d['x']))
[{'y': 2, 'x': 1}, {'y': 4, 'x': 2}]

>>>>>> #lambda is an anonymous function:
... fuc = lambda : 'haha'
>>> print (f())
>>> print (fuc())
haha
>>>

来源:https://blog.csdn.net/EricLeiy/article/details/78712675

标签:python,序列,重复值
0
投稿

猜你喜欢

  • python实现dict版图遍历示例

    2023-11-01 11:43:41
  • Python 如何调试程序崩溃错误

    2022-04-27 15:22:30
  • python os.listdir按文件存取时间顺序列出目录的实例

    2021-03-21 23:02:52
  • 深入了解Python中的变量类型标注

    2023-02-01 09:06:37
  • JS闭包经典实例详解

    2024-05-09 10:20:27
  • python3+selenium实现qq邮箱登陆并发送邮件功能

    2023-02-04 17:54:23
  • mysql增量备份及断点恢复脚本实例

    2024-01-27 04:54:34
  • sql如何删除数据库中数据记录

    2008-10-09 12:31:00
  • Python 添加文件注释和函数注释操作

    2021-07-23 07:16:54
  • js 获取图像缩放后的实际宽高,位置等信息

    2024-05-22 10:41:09
  • 基于python的BP神经网络及异或实现过程解析

    2021-10-29 00:02:01
  • MySQL MEM_ROOT详解及实例代码

    2024-01-15 13:42:54
  • 怎样缩小SQL Server数据库的日志文件

    2009-01-15 13:08:00
  • 使用PHP获取当前url路径的函数以及服务器变量

    2023-10-31 02:31:34
  • Python用zip函数同时遍历多个迭代器示例详解

    2023-09-28 06:09:41
  • Pytho常见的数据可视化库,小白必备

    2022-08-04 15:21:13
  • CentOS 7 安装python3.7.1的方法及注意事项

    2023-03-10 21:23:53
  • Django基础三之视图函数的使用方法

    2022-12-14 07:23:41
  • pytorch使用horovod多gpu训练的实现

    2022-01-07 16:01:18
  • 网易网站设计(思想)

    2009-03-27 17:51:00
  • asp之家 网络编程 m.aspxhome.com