Python操作列表

Python内置列表类型在许多情况下可以满足我们对于数据结构的需求。但是,在一些特定的场景下,可能需要使用其他数据结构来获得更好的效费比。

一、array模块

array 模块提供了一种 array() 对象,它类似于列表,但只能存储类型一致的数据且存储密度更高。下面演示了一个用双字节无符号整数数组来储存整数的例子(类型码为 "H"),而通常的用 Python 的 int 对象来储存整数的列表,每个表项通常要使用 16 个字节:

>>>from array import array
>>>a = array('H', [4000, 10, 700, 22222])
>>>sum(a)
26932
>>>a[1:3]
array('H', [10, 700])

二、collections模块

collections模块提供了一种 deque() 对象,它类似于列表,但从左端添加和弹出的速度较快,而在中间查找的速度较慢。 此种对象适用于实现队列和广度优先树搜索:

>>>from collections import deque
>>>d = deque(["task1", "task2", "task3"])
>>>d.append("task4")
>>>print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = unsearched.popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched.append(m)

在替代的列表实现以外,标准库也提供了其他工具,例如 bisect 模块具有用于操作有序列表的函数:

>>>import bisect
>>>scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>>bisect.insort(scores, (300, 'ruby'))
>>>scores
>>>[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

三、heapq模块

heapq模块提供了基于常规列表来实现堆的函数。 最小值的条目总是保持在位置零。 这对于需要重复访问最小元素而不希望运行完整列表排序的应用来说非常有用:

>>>from heapq import heapify, heappop, heappush
>>>data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>>heapify(data) # rearrange the list into heap order
>>>heappush(data, -5) # add a new entry
>>>[heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
广告合作
QQ群号:707632017

温馨提示:

1、本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。邮箱:2942802716#qq.com。(#改为@)

2、本站原创内容未经允许不得转裁,转载请注明出处“站长百科”和原文地址。

目录