2017-04-18 171 views
0

假設我有一個來自哈利波特魔法生物的按字母順序排列的列表,需要找出列表中的新發現屬於哪個(基於索引)。經過比我不想承認更多的思考,我想出了以下內容:獲取字符串屬於按字母順序排列的字符串列表的索引的最佳方法?

def find_insert_position(name, alpha_list): 

    pos = 0 
    end = len(alpha_list) 
    for n in range(len(name)): 
     for i in range(pos, end): 
      if (pos != end): 
       if ((name[n].lower() > alpha_list[i - 1][n].lower()) and (name[n].lower() <= alpha_list[i][n].lower())): 
        pos == i 


       if ((name[n].lower() < alpha_list[i + 1][n].lower()) and (name[n].lower() >= alpha_list[i][n].lower())): 
        end == i 
      elif (pos == end): 
       return pos 

我敢肯定有更好的方法去了解這一點,我也相當肯定上面甚至沒有正常工作。有什麼建議?

假設 名= '匈牙利樹蜂' 和 alpha_list = [ 'Acromantula', '蛇怪', '駿鷹', 'Merperson', '蟾蜍', '巨魔', '夜騏', '精靈'] 。 所以這個函數會返回整數3,表示索引名稱屬於alpha_list。

+0

你只是想知道的位置,或只是保持列表的字母順序? – Jeremy

+1

知道它所屬的位置。這個函數實際上並不會改變我遵循的列表 – Maccus

回答

4

無論何時您有一個已訂購的清單,並且您想保留該清單,請使用bisect module。這是非常有效的,只是你想要的。

您例如:

from bisect import bisect 

name = 'Hungarian Horntail' 
alpha_list = ['Acromantula', 'Basilisk', 'Hippogriff', 'Merperson', 'Toad', 
       'Troll', 'Thestral', 'Pixie'] 

idx = bisect(alpha_list, name) 
print(idx) # -> 3 

這只是意味着你將不得不在指數3插入namealpha_list保持不變。

如果你比較必須以小寫只有你可以這樣做:

alpha_list_lower = [alpha.lower() for alpha in alpha_list] 
idx = bisect(alpha_list_lower, name.lower()) 
+0

,但這裏的關鍵是我需要返回名稱在alpha_list中的位置的索引,而不是實際上以任何方式更改alpha_list。但是,讓我們說名稱='匈牙利Horntail'和alpha_list = ['Acromantula','Basilisk','Hippogriff','Merperson','蟾蜍','巨魔','Thestral','Pixie']。所以這個函數將返回整數3 – Maccus

+0

@Maccus添加了一個小例子來澄清。希望有所幫助。 –

+0

它似乎對分實際上是一個模塊不是功能?根據我的python 3,至少我認爲你可能會錯誤地使用它,但我會試着弄清楚它!感謝提示芽 – Maccus

0

這裏就是我想要做的:

def find_insert_position(name, alpha_list): 
    names = [i.lower() for i in alpha_list] 
    names.append(name.lower()) 
    names = sorted(names) 
    return names.index(name.lower()) 

name = 'Hungarian Horntail' 
alpha_list = ['Acromantula', 'Basilisk', 'Hippogriff', 'Merperson', 'Toad', 'Troll', 'Thestral', 'Pixie'] 

find_insert_position(name, alpha_list) 

>>> 3 
+0

這工作得很好,但它似乎平分法更清潔,但謝謝你!如果你不能導入,這是要走的路 – Maccus

+0

@Maccus你對'如果你不能導入'是什麼意思? 'bisect'在Python標準庫中;即它自帶了解釋器。如果沒有這樣的模塊,[二進制搜索](https://en.wikipedia.org/wiki/Binary_search_algorithm)仍然是最有效的方法 - 你只需要自己實現它。 –

+0

@hiroprotagonist如果您不知道情況的完整用例,則無法說出最有效的方式。如果@maccus只有一個小的'alpha_list',它可能不會保證寫一個自定義的二進制搜索。因爲它是標準庫的一部分,所以Bisect顯然是清潔/可用性/效率的途徑。爲什麼你想要做出虛假的陳述,而這些虛假的陳述根據可能永遠不會是真實的情況而無法備份? – Jeremy

相關問題