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

1 投票
4 回答
1479 浏览
提问于 2025-04-18 04:59

我刚接触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)。但如果这样不能用来获取下一个项目,那应该怎么做呢?

4 个回答

0

你可以用循环来实现这个功能,但其实把其他代码都放在循环里是浪费的,因为你只需要下一个元素。

有两个不错的方法可以避免这样做:

方法一 - 如果你知道下一个元素的索引,就直接调用它:

my_list[my_index]

虽然大多数情况下你可能不知道索引,但你还是可能想避免使用for循环


方法二 - 使用迭代器

& 查看这个教程

my_iterator = iter(my_list)
next(my_iterator)    # no loop required
0
def markov_chain(list):
    markov = {}
    for index, i in enumerate(list):
        if index<len(list)-1:
            markov[i]=list[index+1]

    return (markov)    

上面的代码接收一个列表作为输入,然后返回一个对应的马尔可夫链,结果以字典的形式呈现。

2

你也可以这样做:

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

这样会把a当作列表中的一个元素,把b当作下一个元素。

2

下面这段代码,稍微简化了一下,应该能满足你的需求。如果有什么地方需要解释,我会详细说明。

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

撰写回答