繁体   English   中英

python函数,用于根据列表中的有序项创建对

[英]python function for creating pairs based on ordered items in list

dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]

使用 python,我正在尝试创建一个对话对数据集,其中集合中的每一对都有发言者 1 和来自发言者 2 的后续响应。使用上面的示例数据,我需要遍历列表和 1) 从合并句子相同的扬声器(如果它们是后续的)并且 2)按照下面的示例创建配对;

输出:

((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))

我如何编写一个函数来接收这样的顺序数据来创建对话对?

conv = []
ls, lm = dat[0]
for s, m in dat[1:]:
    if s == ls:
        lm += ' ' + m
    else:
        conv.append((ls, lm))
        ls, lm = s, m
else:
    conv.append((ls, lm))
    if conv[-1][0] == 1:
        conv.append((2, None))
output = tuple([(conv[i], conv[i+1]) for i in range(0,len(conv) - 1, 2)])

输出:

[((1, 'hello how are you?'), (2, 'I am doing well, thanks!')), ((1, 'Do anything fun this weekend?'), (2, 'I mostly slept but I also played games')), ((1, 'That sounds fun'), (2, None))]

使用这段代码,希望这能解决你的目的

def combine_speaker_lines(id_part_iter):
    conversation = []
    last_speaker, part = id_part_iter[0]
    for speaker, fragment in id_part_iter[1:]:
        if speaker != last_speaker:
            conversation.append((last_speaker, part.lstrip()))
            part = ''
        part += ' ' + fragment
        last_speaker = speaker
    conversation.append((speaker, part.lstrip()))
    return conversation
    return conversation

暂无
暂无

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

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