python - 像列表一样生成字典值

标签 python list dictionary

    sentence="one fish two fish red fish blue fish one 
    red two blue"
    sentence='start '+sentence+' end'
    word_list=sentence.split(' ')
    d={}
    for i in range(len(word_list)-1):
        d[word_list[i]]=word_list[i+1]

    print word_list
    print d

因此,我得到了word_list:

    ['start', 'one', 'fish', 'two', 'fish', 'red',\ 
    'fish', 'blue', 'fish', 'one', 'red', 'two',\ 
    'blue', 'end']

d:

    {'blue': 'end', 'fish': 'one', 'two': 'blue',\
     'one': 'red', 'start': 'one', 'red': 'two'}

但是我需要一个字典,其值看起来像是关键字后面的每个可能单词的列表。例如,单词“fish”后面跟着 4 个单词,所以我需要:

    'fish':['two', 'red', 'blue', 'one']

blue”后跟“fish”和“end

    'blue':['one', 'end']

等等

请问,有什么想法吗?

该任务是生成随机句子的第一步。

谢谢))

最佳答案

你可以尝试这个:

from collections import defaultdict

sentence="one fish two fish red fish blue fish one red two blue"
word_list = sentence.split()

d = defaultdict(list)
for a, b in zip( word_list, word_list[1:]) :
    d[a].append(b)

print d

它给出:

{
    "blue": [ "fish" ], 
    "fish": [ "two", "red", "blue", "one" ], 
    "two": [ "fish", "blue" ], 
    "red": [ "fish", "two" ], 
    "one": [ "fish", "red" ]
}

并且您不需要添加 startend 来避免访问超出列表大小的元素。

关于python - 像列表一样生成字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51798405/

相关文章:

python - Torch 中的 view() 和 unsqueeze() 有什么区别?

python - 访问参数帮助字符串中的 "implicit"元变量值

Python 列表理解嵌套循环

python - 向字典添加键和值

python - 具有可变深度的多级默认字典?

python - 如何修补同一对象的多个方法

python - 在不破坏内存的情况下复制生成器

python - 如何检查列表列表中的数值并返回多个列表?

arrays - Kotlin 中使用 For 循环将 Int 数组元素插入 String 列表的问题(使用了 toString)

java - 将列表映射的所有组合生成为列表列表