Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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 - Fatal编程技术网

如何在Python中引用列表中的下一项?

如何在Python中引用列表中的下一项?,python,Python,我对Python还相当陌生,正在尝试组装一个马尔可夫链生成器。给我带来问题的一点是将列表中的每个单词添加到字典中,并与紧跟其后的单词相关联 def trainMarkovChain(): """Trains the Markov chain on the list of words, returning a dictionary.""" words = wordList() Markov_dict = dict() for i in words:

我对Python还相当陌生,正在尝试组装一个马尔可夫链生成器。给我带来问题的一点是将列表中的每个单词添加到字典中,并与紧跟其后的单词相关联

def trainMarkovChain():
    """Trains the Markov chain on the list of words, returning a dictionary."""
    words = wordList()
    Markov_dict = dict()
    for i in words:
        if i in Markov_dict:
            Markov_dict[i].append(words.index(i+1))
        else:
            Markov_dict[i] = [words.index(i+1)]
    print Markov_dict

wordList()是前一个函数,用于将文本文件转换为单词列表。听起来就是这样。我得到一个错误,说我不能连接字符串和整数,引用words.index(I+1),但如果这不是引用下一项的方法,那么它是如何完成的?

下面的代码稍微简化了一点,应该可以生成您需要的内容。如果有什么需要解释,我会详细说明

words = 'Trains the Markov chain on the list of words, returning a dictionary'.split()
chain = {}
for i, word in enumerate(words):
    # ensure there's a record
    next_words = chain.setdefault(word, [])
    # break on the last word
    if i + 1 == len(words):
        break
    # append the next word
    next_words.append(words[i + 1])

print(words)
print(chain)

assert len(chain) == 11
assert chain['the'] == ['Markov', 'list']
assert chain['dictionary'] == []

下面的代码稍微简化了一点,应该可以生成您需要的内容。如果有什么需要解释,我会详细说明

words = 'Trains the Markov chain on the list of words, returning a dictionary'.split()
chain = {}
for i, word in enumerate(words):
    # ensure there's a record
    next_words = chain.setdefault(word, [])
    # break on the last word
    if i + 1 == len(words):
        break
    # append the next word
    next_words.append(words[i + 1])

print(words)
print(chain)

assert len(chain) == 11
assert chain['the'] == ['Markov', 'list']
assert chain['dictionary'] == []
您还可以通过以下方式执行此操作:

for a,b in zip(words, words[1:]):
这将分配a作为列表中的一个元素,b作为下一个元素。

您也可以这样做:

for a,b in zip(words, words[1:]):
def markov_chain(list):
    markov = {}
    for index, i in enumerate(list):
        if index<len(list)-1:
            markov[i]=list[index+1]

    return (markov)    
这将指定a作为列表中的一个元素,b作为下一个元素。

def markov_链(列表):
def markov_chain(list):
    markov = {}
    for index, i in enumerate(list):
        if index<len(list)-1:
            markov[i]=list[index+1]

    return (markov)    
马尔可夫={} 对于索引,枚举中的i(列表): 如果索引<代码>定义马尔可夫链(列表): 马尔可夫={} 对于索引,枚举中的i(列表):
如果index,您可以使用循环来获得它,但当您只需要下一个元素时,将其余代码放入循环实际上是一种浪费

def markov_chain(list):
    markov = {}
    for index, i in enumerate(list):
        if index<len(list)-1:
            markov[i]=list[index+1]

    return (markov)    
有两个很好的选择可以避免这种情况:

选项1-如果您知道下一个索引,只需调用它: 虽然大多数情况下您不知道索引,但仍然可能希望避免for循环


备选案文2-使用


您可以使用循环来实现这一点,但当您只需要下一个元素时,将其余代码放入循环实际上是一种浪费

def markov_chain(list):
    markov = {}
    for index, i in enumerate(list):
        if index<len(list)-1:
            markov[i]=list[index+1]

    return (markov)    
有两个很好的选择可以避免这种情况:

选项1-如果您知道下一个索引,只需调用它: 虽然大多数情况下您不知道索引,但仍然可能希望避免for循环


备选案文2-使用


使用
enumerate()
获取索引和项目<代码>列表。如果列表中包含重复项,则索引将无法按预期工作。
单词可能重复。
索引(i)+1
是您想要的,但如果存在重复的单词,则此操作将失败。使用
枚举()
可同时获取索引和项目<代码>列表。如果列表中包含重复的项目,索引将无法按预期工作。
单词可能重复。索引(i)+1
是您想要的,但如果有重复的单词,它将失败。这是一个好方法,但
zip(单词,单词[1:])
不会在最后一个单词中压缩,因为
单词[1:
短一个元素。@famousgarkin,但这不是OP想要的,因为他们正在检查下一个元素,所以他们应该在第二个最后一个元素停止,这样就不会引起错误。是的,可能没关系,只是指出以防有人怀疑。为了简单起见,+1。很好的方法,但是
zip(words,words[1:])
不会在最后一个单词中压缩,因为
words[1:
比前一个元素短。@famousgarkin,但这不是OP想要的吗,因为他们正在检查下一个元素,所以应该在最后一个元素停止,这样才不会引起错误。是的,可能没关系,只是指出以防有人怀疑。和+1表示简单。