【问题标题】:Proper Usage of list.append in Python在 Python 中正确使用 list.append
【发布时间】:2013-05-23 19:08:56
【问题描述】:

想知道为什么方法一是正确的,方法二是错误的。

方法一:

def remove_duplicates(x):
    y = []
    for n in x:
        if n not in y:
            y.append(n)
    return y

方法二:

def remove_duplicates(x):
    y = []
    for n in x:
        if n not in y:
            y = y.append(n)
    return y

我不明白为什么第二种方法返回错误的答案?

【问题讨论】:

  • @dm03514:那些不维护秩序,是吗?
  • @Noctua nope 集合是无序的
  • 有人提到套装,但此评论不再存在。如果您想在不更改顺序的情况下加快您的工作,您可以将set()“平行”到您构建的列表中,以使in 操作更快。因此,您使用集合进行查找,而列表用于最终结果。

标签: python


【解决方案1】:

list.append 方法返回None。所以y = y.append(n)y 设置为None

如果这发生在 for-loop 的最后一次迭代中,则返回 None

如果它发生在上一次迭代之前,那么在下一次循环中,

if n not in y

会提出一个

TypeError: argument of type 'NoneType' is not iterable

注意:在大多数情况下,删除重复项的方法比方法 1 更快,但如何操作取决于您是否希望保留顺序、项目是否可订购以及 x 中的项目是否可散列。

def unique_hashable(seq):
    # Not order preserving. Use this if the items in seq are hashable, 
    # and you don't care about preserving order.
    return list(set(seq))

def unique_hashable_order_preserving(seq): 
    # http://www.peterbe.com/plog/uniqifiers-benchmark (Dave Kirby)
    # Use this if the items in seq are hashable and you want to preserve the
    # order in which unique items in seq appear.
    seen = set()
    return [x for x in seq if x not in seen and not seen.add(x)]

def unique_unhashable_orderable(seq):
    # Author: Tim Peters
    # http://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/
    # Use this if the items in seq are unhashable, but seq is sortable
    # (i.e. orderable). Note the result does not preserve order because of
    # the sort.
    # 
    # We can't hash all the elements.  Second fastest is to sort,
    # which brings the equal elements together; then duplicates are
    # easy to weed out in a single pass.
    # NOTE:  Python's list.sort() was designed to be efficient in the
    # presence of many duplicate elements.  This isn't true of all
    # sort functions in all languages or libraries, so this approach
    # is more effective in Python than it may be elsewhere.
    try:    
        t = list(seq)
        t.sort()
    except TypeError:
        del t
    else:
        last = t[0]
        lasti = i = 1
        while i < len(seq):
            if t[i] != last:
                t[lasti] = last = t[i]
                lasti += 1
            i += 1
    return t[:lasti]

def unique_unhashable_nonorderable(seq):
    # Use this (your Method1) if the items in seq are unhashable and unorderable.
    # This method is order preserving.
    u = []
    for x in seq:
        if x not in u:
            u.append(x)
    return u

如果你有 NumPy 并且 seq 中的项目是可订购的,这可能是最快的:

import numpy as np
def unique_order_preserving_numpy(seq):
    u, ind = np.unique(seq, return_index=True)
    return u[np.argsort(ind)] 

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多