简体   繁体   English

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

[英]How to reference the next item in a list in Python?

I'm fairly new to Python, and am trying to put together a Markov chain generator. 我对Python相当陌生,并且正在尝试组合一个Markov链生成器。 The bit that's giving me problems is focused on adding each word in a list to a dictionary, associated with the word immediately following. 让我麻烦的一点是,将列表中的每个单词都添加到字典中,并与紧随其后的单词相关联。

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() is a previous function that turns a text file into a list of words. wordList()是先前的功能,它将文本文件转换为单词列表。 Just what it sounds like. 听起来像什么。 I'm getting an error saying that I can't concatenate strings and integers, referring to words.index(i+1), but if that's not how to refer to the next item then how is it done? 我收到一条错误消息,说我无法连接字符串和整数,引用的是words.index(i + 1),但是如果这不是如何引用下一项,那么它如何完成?

The following code, simplified a bit, should produce what you require. 下面的代码经过简化,应该可以满足您的要求。 I'll elaborate more if something needs explaining. 如果需要解释,我会详细说明。

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'] == []

You can also do it as: 您也可以按照以下方式进行操作:

for a,b in zip(words, words[1:]):

This will assign a as an element in the list and b as the next element. 这将在列表中将a分配为元素,将b分配为下一个元素。

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

    return (markov)    

The code above takes a list as an input and returns the corresponding markov chain as a dictionary. 上面的代码将一个列表作为输入,并返回相应的markov链作为字典。

You can use loops to get that, but it's actually a waste to have to put the rest of your code in a loop when you only need the next element. 您可以使用循环来实现这一点,但是当您只需要下一个元素时,将其余代码放入循环中实际上是一种浪费。

There are two nice options to avoid this: 有两个不错的选择可以避免这种情况:

Option 1 - if you know the next index, just call it: 选项1-如果您知道下一个索引,只需调用它:

my_list[my_index]

Although most of the times you won't know the index, but still you might want to avoid the for loop . 尽管大多数时候您不知道索引,但是仍然可能要避免for循环


Option 2 - use iterators 选项2-使用迭代器

& check this tutorial 并查看本教程

my_iterator = iter(my_list)
next(my_iterator)    # no loop required

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM