【问题标题】:how to get the strings and concat several strings to one string between two index?如何获取字符串并将多个字符串连接到两个索引之间的一个字符串?
【发布时间】:2022-06-29 23:07:49
【问题描述】:

我有一个如下所示的列表:

lst1 = [
'2022-02-21 14:26:02 user1',
'content1',
'content2',
'content3',
'2022-02-24 14:40:12 user2',
'content11',
'content22',
'2022-02-25 14:26:02 user1',
'content12',
'2022-02-24 14:40:12 user2',
'content13'
]

我想将其转换为包含'2022-02-21 14:26:02 user1' 之类的内容作为键及其内容作为对应值的字典。

{
'2022-02-21 14:26:02 user1':'content1;content2;content3',
'2022-02-24 14:40:12 user2':'content11;content22',
'2022-02-25 14:26:02 user1':'content12',
'2022-02-24 14:40:12 user2':'content13'
}

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    这里不需要 pandas,一个简单的 python 循环就可以了:

    d = {}
    key = None
    for x in lst1:
        if x[:4].isdigit():
            key = x
            continue
        if key in d:
            d[key] = d[key]+f';{x}'
        else:
            d[key] = x
    

    输出:

    {'2022-02-21 14:26:02 user1': 'content1;content2;content3',
     '2022-02-24 14:40:12 user2': 'content11;content22;content13',
     '2022-02-25 14:26:02 user1': 'content12'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多