像lis一样生成dict值

2024-04-24 06:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

    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

因此,我得到了单词列表:

    ['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'}

但是我需要一个dict,它的值看起来像是每个可能单词的列表,紧跟在关键字后面。例如,单词“fish”后跟4个单词,因此我需要:

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

蓝色”后跟“”和“结束

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

等等

拜托,有什么想法吗?你知道吗

该任务是生成随机句子的第一步。你知道吗

谢谢)


Tags: 列表forbluered单词onestartsentence
1条回答
网友
1楼 · 发布于 2024-04-24 06:19:20

你可以试试这个:

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来避免访问超出列表大小的元素。你知道吗

相关问题 更多 >