Skip to content
On this page

TIP

python中的列表数据结构的功能扩展

useList

扩展列表,提供了一些常用的方法。

split

将列表按照指定长度分割。

python
def split(origin_list: List, n: int) -> Generator[List, None, None]:
    """
    按指定数量平均分割列表
    :param origin_list: 原始列表
    :param n: 指定数量
    :return: 分割后的列表

    >>> list(UseList.split([1, 2, 3, 4, 5, 6, 7, 8, 9], 3))
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    """
    for i in range(0, len(origin_list), n):
        yield origin_list[i:i + n]

objs_to_obj

将对象列表转换为字典。

python
def objs_to_obj(arr: List[Dict], key: str) -> Dict:
    """
    将对象列表转换为指定key名的对象
    :param arr: 对象列表
    :param key: 指定key名
    :return: 指定key名的对象

    >>> UseList.objs_to_obj([{'id': 1, 'name': 'miclon'}, {'id': 2, 'name': 'miclon2'}], 'id')
    {1: {'id': 1, 'name': 'miclon'}, 2: {'id': 2, 'name': 'miclon2'}}
    """
    return {b[key]: b for b in arr}

dedupe

列表去重,保持顺序

python
def dedupe(items: List, key: Optional[Callable] = None):
    """
    列表去重,保持顺序
    >>> list(UseList.dedupe([1, 5, 2, 1, 9, 1, 5, 10]))
    [1, 5, 2, 9, 10]
    >>> list(UseList.dedupe([{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}], key=lambda d: (d['x'], d['y'])))
    [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]
    """
    seen = set()
    for item in items:
        value = item if key is None else key(item)
        if value not in seen:
            yield item
            seen.add(value)

sort_bubble

冒泡排序。

python
def sort_bubble(collection: List) -> List:
    """
    冒泡排序
    :param collection: 待排序数组
    :return: 排序后数组
    """
    for i in range(len(collection) - 1):
        for j in range(len(collection) - 1 - i):
            if collection[j] > collection[j + 1]:
                collection[j], collection[j + 1] = collection[j + 1], collection[j]
    return collection

sort_quick

快速排序。

python
def sort_quick(collection: List) -> List:
    """
    快速排序
    :param collection: 待排序数组
    :return: 排序后数组

    >>> UseList.sort_quick([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]
    >>> UseList.sort_quick([])
    []
    >>> UseList.sort_quick([-2, 5, 0, -45])
    [-45, -2, 0, 5]
    """
    if len(collection) < 2:
        return collection
    pivot = collection.pop()
    greater: List[int] = []
    lesser: List[int] = []
    for element in collection:
        (greater if element > pivot else lesser).append(element)
    return UseList.sort_quick(lesser) + [pivot] + UseList.sort_quick(greater)

sort

排序。

python
def sort(collection: List, algorithm='bubble') -> List:
    """
    排序
    :param collection: 待排序数组
    :param algorithm: 排序算法, 默认冒泡排序
    :return: 排序后数组
    """
    name = f'sort_{algorithm}'
    if hasattr(UseList, name):
        return getattr(UseList, name)(collection)
    else:
        raise Exception('algorithm not found')

sort_by_list

按指定列表排序,前者列表 按 后者列表排序

python
def sort_by_list(collection: List, sort_list: List) -> List:
    """
    按指定列表排序,前者列表 按 后者列表排序
    :param collection: 待排序数组
    :param sort_list: 指定排序列表
    :return: 排序后数组

    >>> UseList.sort_by_list([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
    [5, 4, 3, 2, 1]
    >>> UseList.sort_by_list(['blue', 'green', 'orange', 'purple', 'yellow'], [3, 2, 5, 4, 1])
    ['yellow', 'green', 'blue', 'purple', 'orange']
    """
    return [val for (_, val) in sorted(zip(sort_list, collection), key=lambda x: x[0])]

min_by

获取列表中最小值。

python
def min_by(collection: List, key: Callable) -> Any:
    """
    获取列表中最小值
    :param collection: 待排序数组
    :param key: 指定排序列表
    :return: 最小值

    >>> UseList.min_by([{'n': 4}, {'n': 2}, {'n': 8}, {'n': 6}], lambda x: x['n'])
    {'n': 2}
    """
    ...

max_by

获取列表中最大值。

python
def max_by(collection: List, key: Callable) -> Any:
    """
    获取列表中最大值
    :param collection: 待排序数组
    :param key: 指定排序列表
    :return: 最大值

    >>> UseList.max_by([{'n': 4}, {'n': 2}, {'n': 8}, {'n': 6}], lambda x: x['n'])
    {'n': 8}
    """
    ...

difference

python
def difference(original_list: List, exclude_list: List, fn: Optional[Callable] = None):
    """
    求差集
    :param original_list: 原数组
    :param exclude_list: 排除数组
    :param fn: 函数
    :return: 差集

    >>> UseList.difference([1, 2, 3], [1, 4])
    [2, 3]
    >>> UseList.difference([{'a': 1, 'b': 2}, {'a': 2, 'b': 3}], [{'a': 1, 'b': 2}])
    [{'a': 2, 'b': 3}]
    >>> UseList.difference([1, 2, 3], [1, 4], fn=lambda x: x ** 2)
    [3]
    """

Released under the MIT License.