2016-11-05 80 views
0

我有一個包含整數的多種列表。我將它們存儲在一個列表(列表清單)中,我稱之爲biglist。找到從其他列表中的項目開始的列表

然後我有第二個列表,例如[1,2]。

現在我想從big_list中找到與小列表相同的項目開始的所有列表。我想查找的列表必須至少包含第二個列表中的所有項目。

我想這可能是完成遞歸,並與該工作示例想出了:

def find_lists_starting_with(start, biglist, depth=0): 
    if not biglist: # biglist is empty 
     return biglist 

    try: 
     new_big_list = [] 
     # try: 
     for smallist in biglist: 
      if smallist[depth] == start[depth]: 
       if not len(start) > len(smallist): 
        new_big_list.append(smallist) 

     new_big_list = find_lists_starting_with(start, 
               new_big_list, 
               depth=depth+1) 
     return new_big_list 
    except IndexError: 
     return biglist 

biglist = [[1,2,3], [2,3,4], [1,3,5], [1, 2], [1]] 
start = [1, 2] 

print(find_lists_starting_with(start, biglist)) 

但是我不是很滿意的代碼示例。

你有什麼建議,如何改善: - 代碼 的可理解性 - 效率

+2

http://codereview.stackexchange.com將是一個更好的地方發佈。 –

回答

4

您可以通過一個迭代嘗試,就像這樣:

[x for x in big_list if x[:len(start_list)] == start_list] 
+0

我認爲這是比上述更好的解決方案 – splinter

1

這裏的我怎麼會寫:

def find_lists_starting_with(start, biglist): 
    for small_list in biglist: 
     if start == small_list[:len(start)]: 
      yield small_list 

這將返回一個發電機來代替,但你可以叫list到它的結果來獲得一個列表。

0

選擇這兩種解決方案(@mortezaipo,@弗朗西斯科 - couzo)目前提出,空間效率可以通過自定義startswith得到改善方法來避免在small_list[:len(start_list)]中構建新的列表。例如:

def startswith(lst, start): 
    for i in range(len(start)): 
     if start[i] != lst[i]: 
      return False 
    return True 

然後

[lst for lst in big_list if startswith(lst, start_list)] 

(@ mortezaipo的解決方案爲藍本)。

相關問題