我有下面列出的例子。我希望获得以下预期输出
example1:
list_for_compare = ['1', '4', '5', '7', '8', '9', '10']
mainlist = ['4', '7', '9']
expected_output1 = [["4", "5"], ["7", "8"], ["9", "10"]]
example2:
list_for_compare = ['1.2.1', '1.2.3', '2.2.5', '3.2.4', '5.4.3', '5.5.1', '5.8.2']
mainlist = ['1.2.2', '2.2.4', '5.4.2']
expected_output2 = [["1.2.2", "1.2.3"], ["2.2.4", "2.2.5", "3.2.4"], ["5.4.2", "5.4.3", "5.5.1", "5.8.2"]]
我尝试在下面的代码中查找中间项
def inbetweenitems_list(mainlist, inbetween):
withmidlist = []
for i in range(len(mainlist)-1):
found = filter(lambda x: mainlist[i] <= x <= mainlist[i+1], inbetween)
withmidlist.append([mainlist[i] , list(found) , mainlist[i+1]])
return withmidlist
输出如下:
example1:
inbetweenitems_list(mainlist, list_for_compare)
output1 = [['4', ['4', '5', '7'], '7'], ['7', ['7', '8', '9'], '9']]
example2:
inbetweenitems_list(mainlist, list_for_compare)
output2 = [['1.2.2', ['1.2.3'], '2.2.4'], ['2.2.4', ['2.2.5', '3.2.4'], '5.4.2']]
我没有找到很多方法来过滤和比较字符串化的数字并获得预期的输出
可以使用正则表达式从字符串中提取所有数字,并将它们转换为元组中的整数。这将使它们可以使用数字内容进行比较
输出:
为了让它运行得稍微快一点,可以使用二进制搜索函数来查找每个值的目标组。
bisect
模块有一个bisect_right
函数,该函数在有序列表中执行二进制搜索并返回索引这就是你要的。这也为第一场比赛之前的所有项目提供了一个条目;如果需要,可以删除输出列表中的顶部条目
输出:
相关问题 更多 >
编程相关推荐