找到从其他列表中的项目开始的列表
问题描述:
我有一个包含整数的多种列表。我将它们存储在一个列表(列表清单)中,我称之为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))
但是我不是很满意的代码示例。
你有什么建议,如何改善: - 代码 的可理解性 - 效率
答
您可以通过一个迭代尝试,就像这样:
[x for x in big_list if x[:len(start_list)] == start_list]
+0
我认为这是比上述更好的解决方案 – splinter
答
这里的我怎么会写:
def find_lists_starting_with(start, biglist):
for small_list in biglist:
if start == small_list[:len(start)]:
yield small_list
这将返回一个发电机来代替,但你可以叫list
到它的结果来获得一个列表。
答
选择这两种解决方案(@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的解决方案为蓝本)。
http://codereview.stackexchange.com将是一个更好的地方发布。 –