EDIT3这个问题可能来得太晚了,因为这个问题已经在一个多月前被接受了,但我还有一件事要补充。在
实际上,Python有一个标准的C-ish链表实现,它是collections模块中的deque类。这是sourceA dequeobject is composed of a doubly-linked list of block nodes.
因此,如果您需要Python中的快速链接列表,请使用deque。在
编辑2基于OP的评论。在...because i want to see what is faster linked list or arrays when i
search information
链表中的搜索复杂度与数组(或基于数组的结构)中的搜索复杂度相等,近似为O(n),其中n是容器中的元素数。但是,由于Python内置的数据结构经过了大量优化和C语言加载,因此在实际使用中,它们的运行速度会快得多。当您需要在列表的任何位置进行固定时间的插入/删除操作时,或者当您不想弄乱动态大小的数组时,链接列表非常有用,但它看起来不像您的情况。由于您实际上是在寻找快速搜索,所以需要一个哈希表,因此使用sets来存储文件名。为此,请替换match_words_and_files中的以下行res.setdefault(word, llist.LinkedList()).insert_with_lookup(file_title)
与
^{pr2}$
编辑。OP更新了请求。如果LinkedList内容保存在名为llist的单独模块中:import os
import llist
def match_words_and_files(directory):
directory = os.path.abspath(directory)
res = {}
for file_name in filter(os.path.isfile, os.listdir(directory)):
file_title = os.path.splitext(file_name)[0]
with open(os.path.join(directory, file_name)) as inp:
for line in inp:
parsed_line = line.rstrip().split()
for word in parsed_line:
res.setdefault(word, llist.LinkedList()).insert_with_lookup(file_title)
return res
原帖。在
如果你想要一个Python中的链表,可以这样实现(显然这不是唯一的方法)class Node(object):
__slots__ = ["_data", "_next_node"]
def __init__(self, data, next_node=None):
self._data = data
self._next_node = next_node
def __str__(self):
return str(self._data)
def __repr__(self):
return repr(self._data)
@property
def data(self):
return self._data
@property
def next_node(self):
return self._next_node
def link_node(self, next_node):
if not hasattr(next_node, "_next_node"):
self._next_node = Node(next_node)
self._next_node = next_node
class LinkedList(object):
def __init__(self, head=None):
if head is not None and not isinstance(head, Node):
self._head = Node(head)
else:
self._head = head
def __repr__(self):
return repr([repr(node) for node in self.iter_links()])
def __str__(self):
return ','.join(str(node) for node in self.iter_links())
def __len__(self):
return sum(1 for _ in self.iter_links())
def set_head(self, head):
self._head = head
def insert(self, node):
if not isinstance(node, Node):
node = Node(node)
node.link_node(self._head)
self._head = node
def insert_with_lookup(self, node):
"""
Inserts a node if the data it contains is not equal to the one
stored in the the head node.
"""
if not isinstance(node, Node):
node = Node(node)
if node.data != self._head.data:
self.insert(node)
def iter_links(self):
current_node = self._head
while current_node:
yield current_node
current_node = current_node.next_node
linked_list = LinkedList(1)
linked_list.insert(2)
linked_list.insert(3)
让我们创造一个,让它成长一点print(list(linked_list.iter_links()))
输出:[3, 2, 1]
p.S
我看不出有任何理由在你的案例中使用链表。在