[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[原创代码] 获取重复的行并且重复的行只保留一次.py

获取重复的行并且重复的行只保留一次.py
  1. """
  2. 获取重复的行并且重复的行只保留一次.py
  3. http://bbs.bathome.net/thread-39502-1-1.html
  4. 2016年2月28日 03:57:29 codegay
  5. 通过help(list),可见python序列有count方法.
  6. -_-基础教程应该有说到的,估计是学过就忘记了.
  7. python3
  8. """
  9. #a.txt内容必须是任意但是有重复行的内容。
  10. #我使用的是一列IP地址进行测试的.
  11. with open("a.txt") as f:
  12.     txt=f.readlines()
  13. #方法一 集合解析,缺点集合无序,不会保持原来的先后顺序
  14. results={r for r in txt if (txt.count(r) >= 2)}
  15. print("一:",results)
  16. #方法二 map filter lambda ,
  17. b=[]
  18. a=map(lambda y:b.append(y) if (y not in b) else None,filter(lambda x:(txt.count(x) >= 2),txt))
  19. list(a)#python3中map等函数返回成生成器,需要list或者for 历遍到的时候才进行计算结果。
  20. print("二:",b)
  21. #方法三
  22. l2=[r for r in txt if txt.count(r)>=2]
  23. result3=[]
  24. [result3.append(r) for r in l2 if r not in result3]
  25. print("三:",result3)
  26. #方法4 字典 不保持原先后顺序
  27. dd={r:txt.count(r) for r in txt}
  28. ll=[k for k,v in dd.items() if v>=2]
  29. print("4",ll)
复制代码
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

返回列表