【问题标题】:Combining multiple lists into dictionary using single list value as key [duplicate]使用单个列表值作为键将多个列表组合到字典中[重复]
【发布时间】:2019-06-03 08:51:47
【问题描述】:

背景: 我正在将用户消息的 PDF 转换为文本文件,并尝试以结构化数据格式重建消息线程。

问题:我已经构建了一个函数,它扫描每一行文本,检测thread_id 并将该行标记为属于适当的thread_id,然后创建一个结构化列表列表像这样:

thread_lines = [['1234567890', 'Dear James,']
                ['1234567890', 'See you soon.']
                ['5558881112', 'Foobar']]

每个内部列表的第 0 项是thread_id。理想情况下,我想创建一个字典,其中每个 thread_id 是一个键,并且相同 thread_id 的所有行都连接在一起作为相应的值。

代码:我有一个函数,我在这里省略了,叫做check_thread,它使用正则表达式来识别thread_id。下面是对每一行进行扫描和分类的小函数。

def thread_create(text):
    thread_lines = []
    thread_id = None
    thread_dict = {}

    for line in range(len( text )):
        # is line beginning of new thread?
        if 'Thread' in text[line]:
            if check_thread(text[line]) != None:
                thread_id = check_thread(text[line])
            elif check_thread(text[line+1]) != None:
                thread_id = check_thread(text[line+1])

        #line belongs to current thread, do something
        if thread_id != None:
            thread_lines.append([thread, text[line]])

谁能提供任何建议,或者以我需要的方式处理这些数据的方法?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    如果我理解正确,应该这样做:

    thread_lines = [['1234567890', 'Dear James,'],
                    ['1234567890', 'See you soon.'],
                    ['5558881112', 'Foobar']]
    
    
    result = {}
    for tid, sentence in thread_lines:
        result.setdefault(tid, []).append(sentence)
    
    print(result)
    

    输出

    {'1234567890': ['Dear James,', 'See you soon.'], '5558881112': ['Foobar']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多