本文介绍了又一个unique()函数......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对序列的唯一()函数的另一种看法。它比我见过的其他人更简洁,适用于所有常见用途

个案(请在食谱页上报告任何错误):




问候,

乔丹

Here''s yet another take on a unique() function for sequences. It''s
more terse than others I''ve seen and works for all the common use
cases (please report any errors on the recipe page):

http://aspn.activestate.com/ASPN/Coo.../Recipe/502263

Regards,
Jordan

推荐答案



看起来很混乱,它是二次时间算法(或者可能是

更糟糕)因为所有list.index和删除操作。


这个版本也是二次的并通过你的测试套件,但

可能会有所不同一些更复杂的案例:


def unique(seq,keepstr = True):

t = type(seq)

if t == str:

t =(list,''''。join)[bool(keeptr)]

见= []

返回t(c代表c,如果(c未见,见。附录(c))[0])

That looks pretty messy, and it''s a quadratic time algorithm (or maybe
worse) because of all the list.index and deletion operations.

This version is also quadratic and passes your test suite, but
might differ in some more complicated cases:

def unique(seq, keepstr=True):
t = type(seq)
if t==str:
t = (list, ''''.join)[bool(keepstr)]
seen = []
return t(c for c in seq if (c not in seen, seen.append(c))[0])




优先:


def unique(seq, keepstr = True):

t = type(seq)

如果t == str:

t =(list,''''。join )[bool(keeptr)]

见= []

返回t(如果没有,则c表示seq中的c(c中看到或看到过.cpend(c)))

Preferable:

def unique(seq, keepstr=True):
t = type(seq)
if t==str:
t = (list, ''''.join)[bool(keepstr)]
seen = []
return t(c for c in seq if not (c in seen or seen.append(c)))




优先:


def唯一(seq,keepstr = True):

t = type(seq)

如果t == str:

t =(list,''''。join)[bool(keeptr)]

见= []

返回t(c代表c)如果没有(c中看到或看到。补充(c)))


Preferable:

def unique(seq, keepstr=True):
t = type(seq)
if t==str:
t = (list, ''''.join)[bool(keepstr)]
seen = []
return t(c for c in seq if not (c in seen or seen.append(c)))



哇,太好了!很酷。 :)


问候,

Jordan

Wow, nice! Very cool. :)

Regards,
Jordan


这篇关于又一个unique()函数......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:27