Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 连接列表中的连续单词_Python_List_Graph_Distance - Fatal编程技术网

Python 连接列表中的连续单词

Python 连接列表中的连续单词,python,list,graph,distance,Python,List,Graph,Distance,我需要连接列表中的连续单词 名单如下: lis = ['hello', 'world', 'I', 'say', 'hello', 'to', 'you'] 如果单词相邻,我就通过一个图(我通过一个类创建)连接它们。 所以“hello”与“world”相连,“world”与“hello”和“I”相连,“I”与“world”和“say”相连 我是这样对python说的 g = Graph() #A graph is described by a proper class. for el

我需要连接列表中的连续单词

名单如下:

lis = ['hello', 'world', 'I', 'say', 'hello', 'to', 'you']
如果单词相邻,我就通过一个图(我通过一个类创建)连接它们。 所以“hello”与“world”相连,“world”与“hello”和“I”相连,“I”与“world”和“say”相连

我是这样对python说的

g = Graph()   #A graph is described by a proper class. 

for el in lis:
    for el1 in lis:
        if abs(lis.index(el) - lis.index(el1)) == 1:  #if the distance is 1
           g.addEdge(el, el1)    #this creates connections 
这是可行的,但如果列表中有相同的单词(在本例中为“hello”和“hello”),则算法只连接两个单词中的第一个(在本例中为第一个“hello”)


我该如何对python说用其他单词也做同样的事情?

一次完成所有事情:

prev = None
for word in lis:
    if prev is not None:
        g.addEdge(prev, word)
    prev = word
如果
None
是有效单词,则可以执行以下操作:

_MISSING = object()
prev = _MISSING


您可以将元素设置为元组
(索引,单词)
,然后
(0,“hello”)
(4,“hello”)
不同:

请注意,您还可以简化邻接测试,例如通过
zip
ping:

for pair in zip(elements, elements[1:]):
其中,
是,例如,
(0,'hello'),(1,'world')

综上所述:

elements = list(enumerate(lis))
for pair in zip(elements, elements[1:]):
    g.addEdge(*pair)

这并不能解决问题,即
图形将例如
addEdge(“say”,“hello”)
解释为添加一个新节点
“say”
,并将其连接到现有节点
“hello”
@jornsharpe-true,但就目前而言,代码中的图形无法知道:-)所有
“hello”
s在OP中看起来也一样。
for pair in zip(elements, elements[1:]):
elements = list(enumerate(lis))
for pair in zip(elements, elements[1:]):
    g.addEdge(*pair)