python - 在列表列表中按索引查找最小值/最大值

标签 python python-3.x

给定大小为 2 的列表列表,我试图找到通过索引确定最小/最大值的最快方法。目标是确定一系列 XY 点的边界/范围。

子列表未排序(按一个索引排序并不能保证另一个索引已排序)。

目前我正在做以下事情:

xy = [(x1, y1), (x2, y2), ..., (xn, yn)]

xs, ys = zip(*xy)
xmax = max(xs)
xmin = min(xs)
ymax = max(ys)
ymin = min(ys)

如果没记错的话,每个操作都是O(n),所以整体复杂度是O(n)。

对于任意大小的列表,是否有更快的方法?

最佳答案

这里有几个替代方法:

def extrema_zip(items):
    split0, split1 = zip(*items)
    return max(split0), min(split0), max(split1), min(split1)
def extrema_key(items):
    return (
        max(items, key=lambda x: x[0])[0],
        min(items, key=lambda x: x[0])[0],
        max(items, key=lambda x: x[1])[1],
        min(items, key=lambda x: x[1])[1])
import numpy as np


def extrema_np(items):
    arr = np.array(items)
    return np.max(arr[:, 0]), np.min(arr[:, 0]), np.max(arr[:, 1]), np.min(arr[:, 1])
import numpy as np


def extrema_npt(items):
    arr = np.array(items).transpose()
    return np.max(arr[0, :]), np.min(arr[0, :]), np.max(arr[1, :]), np.min(arr[1, :])
def extrema_loop(items):
    iter_items = iter(items)
    first = next(iter_items)
    x_min = x_max = first[0]
    y_min = y_max = first[1]
    for x, y in iter_items:
        if x > x_max:
            x_max = x
        elif x < x_min:
            x_min = x
        if y > y_max:
            y_max = y
        elif y < y_min:
            y_min = y
    return x_max, x_min, y_max, y_min
import numpy as np
import numba as nb


@nb.jit(nopython=True)
def _extrema_loop_nb(arr):
    n, m = arr.shape
    x_min = x_max = arr[0, 0]
    y_min = y_max = arr[0, 1]
    for i in range(1, n):
        x, y = arr[i, :]
        if x > x_max:
            x_max = x
        elif x < x_min:
            x_min = x
        if y > y_max:
            y_max = y
        elif y < y_min:
            y_min = y
    return x_max, x_min, y_max, y_min


def extrema_loop_nb(items):    
    arr = np.array(items)
    return _extrema_loop_nb(arr)

以及它们各自的时间作为输入大小的函数:

bm_full bm_zoom

这表明实际上直接循环对您的用例有益。

(提供完整基准 here )


参见 here对于处理 NumPy 数组输入的类似方法。

关于python - 在列表列表中按索引查找最小值/最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59581469/

相关文章:

python - 创建真正巨大的 scipy 数组

python - 将 .csv 文件从 URL 读取到 Python 3.x - _csv.Error : iterator should return strings, not bytes(您是否以文本模式打开文件?)

python - 安装模块后"No module named"错误

python 用数字绘制半三角形

python-3.x - 线程 + 递归(需要 1 个位置参数,但给出了 39 个)

python - 检测用户是否在pygame中按下@登录

python - 如何将文本文件转换为json文件?

python - 值错误 : Too many values to unpack

python - 过滤 Pandas 系列中的特定单词(具有变体)

Python版本/导入困惑