代码之家  ›  专栏  ›  技术社区  ›  twhale

是否有一种计算效率更高的方法可以将数千个列表与边界值进行比较?python

  •  0
  • twhale  · 技术社区  · 6 年前

    我正在比较存储在中的蒙特卡洛模拟生成的数千条路径 a 到一系列边界值 x 两者都有 x 是一系列列表。我的目标是知道有多少条路 a_n 在里面 (n=10000或更多)永远不会低于每个边界值 x1 .... x7 (这里, x1。。。。x7 是平缓向上倾斜的直线)。

    从视觉上看,数据看起来像下面这样,其中红线表示中的一个边界值 x 圆锥线代表 (可能有7条这样的红线,我想知道锥体中有多少条线 永远不要低于每一条红线 x 因此,该算法的示例输出可以是: (941, 922, 893, 851, 384, 191) .)

    目前,我正在使用列表理解进行比较。然而,当数据集变大时(比如n=10000或更多) )这变得非常缓慢。是否有计算上更有效的方法来实现相同的结果?

    Visual representation of x and a.

    列表理解的代码如下所示。

    x = [[10, 11], [14, 12]]
    a = [[9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16]]
    
    def touch(x, a):
        return [[all([asel > xsubel for xsubel in xel for asel in ael]) for ael in a].count(False) for xel in x ]
    touching = touch(x, a)
    

    编辑

    我希望从上面的简化示例中得到以下结果 x 是: [2, 6] 。我正在比较中的每个列表 x ,第1项 至第1项 x ,第2项 至第2项 x 因此:a1_1(9)(a的列表1中的项目1)低于x1_1(10)。a1_ 2(10)等于x1_2(10)-因此这是两次违反条件。a3_1(11)>x1_1(10)和a3_2(12)>x1_2(11)和a中的其他列表也高于它们对应的元素。对于x2(x中的第二个列表):除了a7之外,a中的所有列表都较低,其中a7_1(15)高于x2_1,a7_2高于x2_2。因此 [2, 6] .

    0 回复  |  直到 6 年前
        1
  •  0
  •   AirSquid    6 年前

    我很难捕捉到你的标准…:)。你在上面的评论中加入了一个“和/或”的陈述,这很令人困惑。

    这是有效的,并显示了中间结果。你可以在打印声明正常工作后将其删除。

    这里的比较是针对中的相应项目 a 严格低于相应项目 x ,正确答案为(1,2)。[我在上面的评论是不正确的……没有仔细考虑]

    # line compare
    
    import numpy as np
    
    x = [[10, 11], [14, 12]]
    a = [[9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16]]
    
    a = np.array(a)
    x = np.array(x)
    
    result = []
    for row in x:
        passing = np.all(a<row, axis=1)
        print(f'for element in x: {row} the correspoinding a elements pass: {passing}')
    
        result.append(np.sum(passing))
    
    print(result)
    

    产量:

    for element in x: [10 11] the correspoinding a elements pass: [ True False False False False False False]
    for element in x: [14 12] the correspoinding a elements pass: [ True  True False False False False False]
    [1, 2]
    
        2
  •  0
  •   AirSquid    6 年前

    使用numpy数组比较所有数据应该更快 a 中每行的元素 x 在矢量化操作中

    # line compare
    
    import numpy as np
    
    x = [[10, 11], [14, 12]]
    a = [[9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16]]
    
    a = np.array(a)
    x = np.array(x)
    
    result = []
    for row in x:
        passing = np.sum(np.all(a>row, axis=1))   # sum all rows where att a>row in x
        result.append(passing)
    
    print(result)
    

    产量:

    [5, 1]