2012-09-26 15 views
0

對Python很新穎,並且一直在使用列表和排序成員。我的問題是,如果我有隨機的字符串列表(長度相等的所有字符串):使用具有多個關鍵參數的L.sort排序字符串列表

li=["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"] 

,現在我想根據一些排名,我用下面的函數定義排序該列表:

def rank_string(str1,str2): 
    rank=0 
    for i in range(len(str1)): #all strings will be checked to be equal length 
     if (str1[i]==str2[i]): 
      rank += 1 
    return rank 

,現在我想起來使用此功能與目標串排序我的名單,所以我嘗試以下方法:

target_string="stripe" 
df = lambda x:rank_string(x,target_string) 
sorted_list = resultlist.sort(key=df) 

我的印象中,所有列表值將給予之後的關鍵排名函數的一個通過,然後按照這個排序?這會運行,但sorted_list的值爲None。我假設那是一個n00b,我錯過了一些基本的東西。什麼? :-)

感謝您的幫助提前。

回答

1

.sort()方法在原地排序並且不返回任何內容。

使用sorted()而不是如果您想要返回排序列表並且原始輸入列表保持不變。

>>> a = [2, 3, 1] 
>>> a.sort() 
>>> a 
[1, 2, 3] 
>>> b = [2, 3, 1] 
>>> sorted(b) 
[1, 2, 3] 
>>> b 
[2, 3, 1] 
+0

沒錯!按我的預期工作。謝謝。 – Englishbob

0

resultlist.sort是列表的方法中,代替排序resultlist,並返回None

sorted_list = sorted(li, key=df) 應該這樣做。

1

正如其他人所說,sorted()將返回一個新的列表。您的代碼看起來是這樣的:

li = ["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"] 
target_string = "stripe" 

sorted_list = sorted(li, key=lambda x: sum(1 for c1,c2 in zip(x, target_string) if c1==c2)) 

回報['hgjtud', 'iernfd', 'scoeps', 'stiiss', 'stripe']

+0

我開始意識到,簡潔是非常pythonesque :-)是要走的路。謝謝。 – Englishbob

1

像其他人說,使用sorted()。你也可以讓事情更短:

from functools import partial 

def rank_string(str1, str2): 
    return sum(a == b for a, b in zip(str1, str2)) 

li = ["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"] 
sorted_list = sorted(li, key=partial(rank_string, "stripe")) 

[編輯]

from operator import eq 

def rank_string(str1, str2): 
    return sum(map(eq, str1, str2)) 

:-)

[/編輯]

+0

再次,我想簡單與熟悉.-) – Englishbob

+0

@Englishbob:關於簡潔,請參閱我的編輯。 – pillmuncher