NPE*_*NPE 6 python sorting list unique python-2.2
在Python 2.2中(不要问),排序列表和删除重复项的最佳方法是什么?
我显然可以写一个函数sort()然后迭代,但我想知道是否有一个惯用的单行.
编辑:列表很短,因此效率不是问题.此外,元素是不可变的.
对于旧的python版本,并且因为你正在使用字符串,所以没有我能想到的单行程,但是使用字典可能是这样的模式:
def sorted_uniq(your_list):
table = {}
for s in your_list:
table[s] = None
k = table.keys()
k.sort()
return k
Run Code Online (Sandbox Code Playgroud)
改编自一个古老的ActiveState代码片段线程,Alex Martelli自己写了几条评论:http://code.activestate.com/recipes/52560/
列表推导的一种较短的方式:
def sort_uniq(alist):
d = {}
mod_list = [d.setdefault(i,i) for i in alist if i not in d]
mod_list.sort()
return mod_list
Run Code Online (Sandbox Code Playgroud)
除了史蒂文的整洁(但略微没有吸引力)的一个衬垫,我认为这是朝着最少的线和最惯用的方式使用Python 2.2:
感谢Steven Rumbalski在评论中,第二个版本可以通过python的zip功能进一步浓缩:
def sort_uniq(alist):
mod_list = dict(zip(alist,alist)).keys()
mod_list.sort()
return mod_list
Run Code Online (Sandbox Code Playgroud)
如果list.sort()没有副作用,我们有一个班轮.;)
惯用语和单行程?没有.
这是一个非惯用的对接丑陋的单线.
>>> x = [4, 3, 3, 2, 4, 1]
>>> [y for y in (locals().__setitem__('d',{}) or x.sort() or x)
if y not in d and (d.__setitem__(y, None) or True)]
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
如果可以接受简单的双线程:
x = [4, 3, 3, 2, 4, 1]
x = dict(map(None,x,[])).keys()
x.sort()
Run Code Online (Sandbox Code Playgroud)
或者制作两个小辅助函数(适用于任何序列):
def unique(it):
return dict(map(None,it,[])).keys()
def sorted(it):
alist = [item for item in it]
alist.sort()
return alist
print sorted(unique([4, 3, 3, 2, 4, 1]))
Run Code Online (Sandbox Code Playgroud)
给
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
最后,一个半圆形的衬垫:
x = [4, 3, 3, 2, 4, 1]
x.sort() or [s for s, t in zip(x, x[1:] + [None]) if s != t]
Run Code Online (Sandbox Code Playgroud)