uniq 基本上就是用python來干不sort的sort -u

Python/PHP/Perl 开发与设计
回复
头像
millenniumdark
论坛版主
帖子: 4159
注册时间: 2005-07-02 14:41
系统: Ubuntu 14.04 (Kylin)
送出感谢: 42 次
接收感谢: 9 次
联系:

uniq 基本上就是用python來干不sort的sort -u

#1

帖子 millenniumdark » 2012-11-16 18:39

如題

代码: 全选

#!/usr/bin/env python3.1

# written by Jakukyo Friel <weakish@gmail.com>
# under GPL v2

# omit repeated lines, 
# i.e. 'sort | uniq' or 'sort -u' without reordering. 

# I want to be unique,
# not sort of unique.
# I only want you,
# not sort of you.


import functools

def uniq(uniqlines, line):
  '''
  >>> uniq((), 1)
  (1,)
  >>> uniq((1,), 2)
  (1, 2)
  >>> uniq((1, 2), 2)
  (1, 2)
  '''
  return uniqlines if line in uniqlines else uniqlines + (line,)

def uniq_lines(lines):
  '''
  >>> tuple(uniq_lines((3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3)))
  (3, 1, 4, 5, 9, 2, 6, 8, 7)
  '''
  return functools.reduce(uniq, lines, ())

def unit_test():
  import doctest
  doctest.testmod()


def main():
  import sys
  unit_test()
  print('\n'.join(uniq_lines(sys.stdin.read().split('\n'))))

if __name__ == '__main__':
  main()

放在gitcafe上 https://gitcafe.com/weakish/uniq/blob/master/uniq.py
回复

回到 “Python/Php/Perl”