Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
挑战Python列表交叉点_Python_List_Math_Set_Intersection - Fatal编程技术网

挑战Python列表交叉点

挑战Python列表交叉点,python,list,math,set,intersection,Python,List,Math,Set,Intersection,我有两份清单如下: list_1 = [ [4,9], [10,14], [18,20], [21,23]] list_2 = [ [3,5], [6,9], [10,11], [12,13], [14,16], [17,23] ] 我需要用这些规则找到这两个的交集: 列表中的所有数字都已排序 任何列表中都没有0或负数 仅选择范围差>=2的交点 因此,使用上述规则,相交结果应为: [ [6,9], [18,20],[21,23] ] 我在这张图中通过在一行上分布数字来表示这个问题: 更新:

我有两份清单如下:

list_1 = [ [4,9], [10,14], [18,20], [21,23]]
list_2 = [ [3,5], [6,9], [10,11], [12,13], [14,16], [17,23] ]
我需要用这些规则找到这两个的交集:

  • 列表中的所有数字都已排序
  • 任何列表中都没有0或负数
  • 仅选择范围差>=2的交点
  • 因此,使用上述规则,相交结果应为:

    [ [6,9], [18,20],[21,23] ]
    
    我在这张图中通过在一行上分布数字来表示这个问题:


    更新:根据您的定义,在下面发布了我自己的答案,我得到的广义交叉点是:

    list_1 = [ [4,9], [10,14], [18,20], [21,23]]
    list_2 = [ [3,5], [6,9], [10,11], [12,13], [14,16], [17,23] ]
    list_range1 = [item for sublist in [range(a, b+1) for a,b in list_1] for item in sublist]
    list_range2 = [item for sublist in [range(a, b+1) for a,b in list_2] for item in sublist]
    c = list(set(list_range1) & set(list_range2))
    c.sort()
    ans1 = [a for a in list_1 if (a[0] in c and a[1] in c)] + [a for a in list_2 if (a[0] in c and a[1] in c)]
    ans2 = [a for a in ans1 if not a[0] == a[1]-1 ]
    
    如果正确(不确定,因为不确定我是否得到了问题),您的示例的答案也应该包含

    [[4, 9], [10, 14]]
    
    如清单2[3,5]所示,[6,9]与[3,9]无法区分。
    如果你想区分它们,你应该对每个列表的第二个项做-1,然后加上+1。

    好的,我用启发式方法得到了解决方案,但我确信这并不漂亮:(

    [[6,9],[18,20],[21,23]


    请向我们展示您为解决问题而编写的代码!我不理解规则。为什么是
    [14,16]
    [18,20]
    [20,23]
    应该在结果中吗?那里根本没有交叉点。你有没有研究过
    itertools.permutations
    /
    itertools.combines
    作为一种生成所有可能的组合,然后使用规则进行过滤的方法?关于规则3:“范围差异”–到底有什么区别?我觉得如果你花时间更明确地定义你的“范围差异”标准,你可以回答你自己的问题…谢谢你的片段。但是[4,9]不能在交叉点,如清单2所示,你可以看到5到6之间有差距
    def intersect_windows(list_1, list_2):
      if not list_1 or not list_2:
        return []
    
      list_1 = [range(x[0], x[1]) for x in list_1]
      list_2 = [range(x[0], x[1]) for x in list_2]
    
      result = []
    
      for s1 in list_1:
        for s2 in list_2:
          intr = [max(s1[0], s2[0]), min(s1[-1], s2[-1])+1]
          if (intr[1] - intr[0]) >= 2:
            result.append(intr)
    
      return result
    
    ##Usage
    
    list_1 = [ [4,9], [10,14], [18,20], [21,23]]
    list_2 = [ [3,5], [6,9], [10,11], [12,13], [14,16], [17,23] ]
    intersect_windows(list_1, list_2)