首页 > 解决方案 > 根据值的不同长度将键和值数组分解为多个数组

问题描述

假设我有一个以下方式的 Python 列表:

['Comment by user14 [ 12/Apr/06 ]',
 'Although I wish could have a few more buttons',
 'Comment by user14 [ 12/Apr/06 ]',
 'I am satisfied with the changes',
 'Comment by user14 [ 12/Apr/06 ]',
 'I just received a call stating the issue has been resolved',
 'Comment by user12 [ 11/Apr/06 ]',
 'Nothing is responding', 
 'Please revert ASAP',
 'Comment by user50 [ 10/Apr/06 ]',
 'None of the tabs are loading any data.',
 'Comment by user54 [ 10/Apr/06 ]',
 'This seems very weird! I am not able to access any of the ',
 'changes that I made to this table yesterday. I wonder what is',
 'going on. Someone needs to have a look into this.',
 'Comment by user56 [ 09/Apr/06 ]',
 'Unable to access the shared drive.']

我希望这张表被分解成列表,如 -

['Comment by user14 [ 12/Apr/06 ]',
 'Although I wish could have a few more buttons']
['Comment by user14 [ 12/Apr/06 ]',
 'I am satisfied with the changes']
['Comment by user14 [ 12/Apr/06 ]',
 'I just received a call stating the issue has been resolved']
['Comment by user12 [ 11/Apr/06 ]',
 'Nothing is responding']
['Comment by user12 [ 11/Apr/06 ]',
 'Nothing is responding', 
 'Please revert ASAP']
['Comment by user54 [ 10/Apr/06 ]',
 'This seems very weird! I am not able to access any of the ',
 'changes that I made to this table yesterday. I wonder what is',
 'going on. Someone needs to have a look into this.']
etc

可能吗?我无法想出一个逻辑。'Comment by ...' 是键,后面的行是注释。这些行可以是一个或多个,并且同一用户在同一天可以多次出现“评论...”行,我希望是否有办法获得每一天的价值。提前致谢!

标签: pythonlist

解决方案


这应该有效:

def is_header(text):
    return text.lower().startswith("comment by")

data_split = [] if is_header(data[0]) else [[]]

for item in data:
    if is_header(item):
        data_split.append([item])
    else:
        data_split[-1].append(item)
        

推荐阅读