2013-05-28 4 views
4

Как знать, почему метод 1 правильный, а метод 2 неверен.Правильное использование list.append в Python

Method1:

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

Метод 2:

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

Я не понимаю, почему второй метод возвращает неправильный ответ?

+1

@ dm03514: Те, не сохраняют порядок, не так ли? – Noctua

+0

@ Наборы Noctua nope неупорядочены – dm03514

+1

Возможный дубликат [Добавляющий элемент к спискам - python] (http://stackoverflow.com/questions/2505529/appending-item-to-lists-python) –

ответ

16

Метод 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 и элементы в последовательности являются упорядочиваема:

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

спасибо за быстрый ответ ... – lakesh

Смежные вопросы