我正在编写一个包含一些有用函数的脚本来编辑双链表,并且我不使用OOP。所以没有使用类。
以下是一个双链接列表的示例:
dll = ['So true', ['^very much', ['try it', ['Not yet', None, [...]], [...]], [...]], None]
请注意,ddl元素的结构类似于:[string,指针指向上一个节点,指针指向下一个节点]
我正在尝试创建一个变量,该变量的值为双链表中的字符'^'
作为"游标"(只是一个虚拟游标,但它实际上只是'^'
字符的索引(,而不使用类(一个函数,或者两个函数?(。现在,"cursor"变量是指向节点(包含当前字符串(和该字符串中的位置的指针。
我想创建它的原因是用它来创建有用的功能,比如:将光标向左移动一个字符,将光标移动到行的开头,。。。等
cursor=带字符串的双链接列表中"^"的索引。
所以我的问题是:如何在不使用类的情况下找到双链表中字符串中字符的索引?
只想找到^
字符的位置,可以使用一个简单的递归函数来连接所有字符串(我假设所有字符串都在嵌套列表中的位置0(:
def join_nested_strings(list):
if list[1]:
return list[0] + join_nested_strings(list[1])
else:
return list[0]
然后简单地找到具有CCD_ 4的索引。
编辑:
如果您想要元组(字符串、索引(形式的结果,递归函数如下所示:
def cursor(list):
if "^" in list[0]:
return list[0], list[0].index("^")
else:
return cursor(list[1])
请注意,如果任何字符串中都不包含光标字符,则此简单函数将引发错误。
首先,这里有一个函数,它可以从元素列表中创建双链接列表。假设我们有一个字符串元素列表:
testList =['A lot', 'Very ^much', 'Try it', 'Nop']
现在,为了从testList
构建双链接列表,我们如下所示:
# Build node function
def getNode(data):
return [data, None, None]
# Build the doubly linked list
def construct_double_list(testList):
nxt, prvs = 1, 2
start, end = None, None
for line in testList:
next_node = getNode(line)
if start is not None:
end[nxt] = next_node
next_node[prvs] = end
end = next_node
else:
start = next_node
end = next_node
return start, end
如果您运行上面的函数生成器,则双链表(双向可迭代(将为:
dll = dll = ['A lot', ['Very ^much', ['Try it', ['Nop', None, [...]], [...]], [...]], None]
我昨天已经这样做了,但今天早上我在解决光标问题时遇到了麻烦。过了一段时间,我终于开始工作了。以下是创建一个光标作为指向节点(包含当前行(和该行内位置的指针的函数:
def cursor():
cursor = (None, None)
start, end = construct_double_list(testList)
node = start
while node is not None:
line = node[0]
if '^' in line:
pointer1 = node
pointer2 = line.index('^')
node = node[1]
cursor = (pointer1, pointer2)
return cursor
如果您打印上面的cursor()
功能:
print(cursor())
你得到:
(['Very ^much', ['Try it', ['Nop', None, [...]], [...]], ['A lot', [...], None]], 5)
# Node 1 and string index 5
现在我可以创建一些有用的函数来编辑数据,修改,添加,删除,交换元素,交换双链表字符串元素中的字符。。。等