2015-11-13 34 views
-2
def rearrangelist(list): 
    lst = input["list"] 
    lst = ['list'[0]:1,'list'[1]:0,'list'[2]:3]; 
    print (sorted(list)) 

我怎樣才能使這項工作不使用拉姆達,一旦我基本上要在列表中的元素根據每個列表元素被定義的數字是重新排列,每例如:如何在不使用lambda的情況下按第二個元素排序列表?

list = [john, peter, olive] 
john[2], peter [1] and olive[0] 

而且我想這個根據該打印數此進行排序:

olive, peter, john 

不容使用 「郵編()」 函數

+9

如果您不想使用匿名函數 - 將其命名。 –

+2

爲什麼限制不使用lambda? –

+1

你的例子沒有意義。你能發佈適當的代碼和數據例子嗎? –

回答

0

可以使用decorate-sort-undecorate idiom

>>> names = ['john', 'peter', 'olive'] 
>>> order = [2, 1, 0] 

>>> decorated = zip(order, names) 
>>> decorated 
[(2, 'john'), (1, 'peter'), (0, 'olive')] 

>>> sorted_decorated = sorted(decorated) 
>>> sorted_decorated 
[(0, 'olive'), (1, 'peter'), (2, 'john')] 

>>> undecorated = zip(*sorted_decorated)[1] 
>>> undecorated 
('olive', 'peter', 'john') 

如果您不能使用ZIP:

>>> decorated = [(order[index], names[index]) for index in range(len(order))] 

和:

>>> undecorated = [value[1] for value in decorated_sorted] 
+0

不能使用zip,對不起 – rockethon

+0

你的代碼對Python 3.5.0不是字 – rockethon

+0

我沒有Python3.5。它以什麼方式不起作用?哪條線?什麼錯誤? –

0

sorted(iterable[, cmp[, key[, reverse]]]) Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

key是你需要的。供應它會返回一個比較關鍵

def SortBySecondElement(Element): 
    return Element[1] 

呼叫分類方法,這種方法

sorted(list, key=SortBySecondElement) 

我希望這是你想要的功能。

+1

而不是定義自己的函數,你可以在'operator module'中使用'itemgetter':sorted(list,key = operator.itemgetter(1)) – mnencia

+0

@mnencia你是對的,這個解決方案比我提供的更簡潔。 – hrust

1

最簡單的方法是使用operator.itemgetter功能

from operator import itemgetter 

print(sorted(list, key=itemgetter(1))) 

順便說一句,list是一個可怕的變量名稱,因爲它會影響列表類型。

+0

我剛剛給這個名字,例如建議。謝謝 – rockethon

相關問題