如何将特定的普通列表转换为嵌套列表

2024-10-02 22:24:41 发布

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

问题背景:

基本上,我正在制作一个“聊天机器人”,我想从一个文本文件向它提供大量数据。在本例中,0表示人类,1表示聊天机器人。列表总是以人类对话开始,人类和机器人都可以有多重反应。根据可能的回答列表,我想生成所有可能对话的列表。我知道这可以通过递归来实现,但我就是不知道该怎么做:( 最好用伪代码或python来回答这个问题。不过,我对任何编程语言都持开放态度

示例:

Given: [ [0, "Hello"], [0, "Good morning"], [1, "Beep bop Im a bot"], [1, "Hello, dear human"], [0, "Okay, what time is it?" ]
Output: [ 
["Hello", "Beep bop Im a bot", "Okay, what time is it?"],
["Hello", "Hello, dear human", "Okay, what time is it?"],
["Good morning", "Beep bop Im a bot", "Okay, what time is it?"],
["Good morning", "Hello, dear human", "Okay, what time is it?"],
]

Tags: hello列表timeisbot机器人it人类
2条回答

使用字典有什么好处?您可以添加键列表(人类句子)及其值(机器人响应)。我想把句子分成几类是必要的,这样才能进行合理的对话

比如说

import random
from datetime import date

human_greetings = ['hi', 'hello']
robot_greetings = ['hello human', 'hi buddy']
talk = dict()

talk['time'] = ['It is...']
talk['date'] = [('Today is ' + str(date.today()))]


for greeting in human_greetings:
    talk[greeting] = robot_greetings

while True:
    human = str(input())
    robot = random.choice(talk[human])
    print(robot)

您正在寻找一个简单的定向图中的最长路径,如下所示:

"Hello"    ->\ /->"Beep bop Im a bot"->\
                 X                         X >"Okay, what time is it?"
"Good morning"->/ \->"Hello, dear human"->/

因此,您正在以下位置中寻找替代路径:

given = [ [0, "Hello"], [0, "Good morning"], [1, "Beep bop Im a bot"], [1, "Hello, dear human"], [0, "Okay, what time is it?" ] ]

这里的递归答案很自然:

  • 如果given为空,则只有一个空路径
  • 如果given不是空的,则让head, tail作为given的第一个元素,并分别作为given的其余元素。你有三种可能:
    1. 如果tail为空,则唯一路径为[head.sentence]
    2. 否则,如果head.speaker != first element tail.speaker,则为tail中的每个路径生成[head.sentence] + path
    3. 否则,如果head.speaker == first element tail.speaker,则: A.在tail中产生路径(递归调用) B删除tail的第一个元素并循环到3。直到你在案例1中。或2

它为什么有效?(演示示意图):

(I)你有:given[0].speaker == path.speaker对于paths(given)中的每一个path。如果given只有一个元素,则为真。否则,您将生成路径head.sentence + <something> == given[0].sentence + <something>,或者在paths(tail)中生成一个path,其中tail[0].speaker == head.speaker == given[0].speaker

  • 旋转:在案例1中,您只直接生成一个元素。或者2,当head.sentence后面跟着paths(tail)并且尾部第一个元素的说话人不同于head的说话人时。假设命题(I),你可以肯定一个人的句子后面总是跟着一个计算机句子,反之亦然
  • 完整性:这对于空路径是正确的,因为您尝试了所有可能的开始,因为您在每个元素上调用paths,直到出现旋转为止

在python中:

given = [ [0, "Hello"], [0, "Good morning"], [1, "Beep bop Im a bot"], [1, "Hello, dear human"], [0, "Okay, what time is it?" ] ]

def paths(L):
    if L:
        head, *tail = L
        while tail and tail[0][0] == head[0]:
            yield from paths(tail)
            _, *tail = tail

        for path in paths(tail):
            yield [head[1]] + path
    else:
        yield []

print(list(paths(given)))

输出:

[['Good morning', 'Hello, dear human', 'Okay, what time is it?'], ['Good morning', 'Beep bop Im a bot', 'Okay, what time is it?'], ['Hello', 'Hello, dear human', 'Okay, what time is it?'], ['Hello', 'Beep bop Im a bot', 'Okay, what time is it?']]

相关问题 更多 >