我有一個包含整數的多種列表。我將它們存儲在一個列表(列表清單)中,我稱之爲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))
但是我不是很滿意的代碼示例。
你有什麼建議,如何改善: - 代碼 的可理解性 - 效率
http://codereview.stackexchange.com將是一個更好的地方發佈。 –