2014-07-03 155 views
1

我想根據另一個列表的值排序一個列表的索引。我的代碼是:根據另一個列表值對列表的索引值進行排序

x = ['mango','orange','butter','milk','coconut','tree','sky','moon','dog','cat','ant','pop','fog'] // sort this list 
    y = ['1','10','11','12','13','2','3','4','5','6','7','8','9'] 

什麼我做的是:

>>> x.sort(key=lambda (a,b): y.index(a)) 
     Traceback (most recent call last): 
     File "<stdin>", line 1, in <module> 
     File "<stdin>", line 1, in <lambda> 
     ValueError: too many values to unpack 

我期望的結果是:

x = ['mango','cat','ant', 'pop', 'fog','orange','butter','milk','coconut','tree','sky','moon','dog'] 
+0

..這真的是你想要的結果嗎? – DSM

+0

你想要的輸出對我來說不對。嘗試:'zip(* sorted(zip(x,y),key = lambda z:int(z [1])))[0]' –

+0

是的,這是我期望的結果,'y'表示的索引號 - 1. – user227666

回答

1

我認爲你的貓關閉了。

>>> new = [x[int(index) - 1] for index in y] 
>>> new 
['mango', 'cat', 'ant', 'pop', 'fog', 'orange', 'butter', 'milk', 'coconut', 'tree', 'sky', 'moon', 'dog'] 
+0

是的,我認爲是這樣 – user227666

+0

@ user227666好的,我看到你在你的問題中修復它。請注意,python列表從索引0開始,這就是爲什麼我從'y'中的值減去1的原因。 – timgeb

+0

我不明白這個輸出。基於第二個列表,「貓」在索引6處,爲什麼列在第二位? – CoryKramer

0

嘗試走索引和項目一起,排序和獨立:

y = [int(index) for index in y] # need to sort numerically, not alphabetically 
x = [item for index, item in sorted(zip(y, x))] 

這是排序的不對因爲元組通過第一個鍵(索引)進行排序,然後將正確的條目順序作爲此類副產品提取出來。

相關問題