【发布时间】:2014-02-11 06:14:25
【问题描述】:
我正在尝试根据索引的位置合并两个列表,所以有点接近交叉点。
在这种情况下,集合不起作用。我要做的是匹配每个列表中的索引,然后如果该元素比其他列表中的元素少一个,那么我才会收集它。
一个例子将更好地解释我的场景。
示例输入:
print merge_list([[0, 1, 3], [1, 2], [4, 1, 3, 5]],
[[0, 2, 6], [1, 4], [2, 2], [4, 1, 6]])
样本输出:
[[0,2],[4,6]]
所以在 list1 的位置 0 上,我们有 1、3,而在 list2 中,我们有 2、6。因为 1 比 2 小一,所以我们收集它并继续前进,现在 3 小于 6,但它不是少一比即不是 5 所以我们忽略它。接下来我们有 [1, 2][1, 4],所以索引/位置都是 1,但 2 不小于 4,所以我们忽略它。接下来我们在 list2 中有 [2, 2] 两个索引 2 都不匹配第一个列表中的任何索引,所以没有比较。最后我们有 [4, 1, 3, 5] [4, 1, 6] 比较。两个索引都匹配,并且列表一中只有 5 比列表二少 1,因此我们收集了 6 个因此我们收集 [4,6] 表示索引 4 和匹配等。
我试图让它工作,但我似乎没有让它工作。
这是我目前的代码。
def merge_list(my_list1, my_list2):
merged_list = []
bigger_list = []
smaller_list = []
temp_outer_index = 0
temp_inner_index = 0
if(len(my_list1) > len(my_list2)):
bigger_list = my_list1
smaller_list = my_list2
elif(len(my_list2) > len(my_list1)):
bigger_list = my_list2
smaller_list = my_list1
else:
bigger_list = my_list1
smaller_list = my_list2
for i, sublist in enumerate(bigger_list):
for index1 , val in enumerate(sublist):
for k, sublist2 in enumerate(smaller_list):
for index2, val2 in enumerate(sublist2):
temp_outer_index = index1 + 1
temp_inner_index = index2 + 1
if(temp_inner_index < len(sublist2) and temp_outer_index < len(sublist)):
# print "temp_outer:%s , temp_inner:%s, sublist[temp_outer]:%s, sublist2[temp_inner_index]:%s" % (temp_outer_index, temp_inner_index, sublist[temp_outer_index], sublist2[temp_inner_index])
if(sublist2[temp_inner_index] < sublist[temp_outer_index]):
merged_list.append(sublist[temp_outer_index])
break
return merged_list
【问题讨论】:
-
[[1, 3], [2], [], [], [1, 3, 5]]和[[2, 6], [4], [2], [], [1, 6]]作为输入会不会更有意义,所以 index 是一个实际的索引? -
@poke,感谢您的评论。在我的其他代码中,我们构建了这些,我只构建了带有数据的代码,即没有 [] 列表。我知道它更容易制作,但不是必需的,我认为有点没有效率等。