Grouping list in python

Viewed 76

How can I transform a list A to list B by grouping with the value is continuous? It means 'timeStart_timeEnd_itemName' if first timeEnd equal next loop timeStart and itemName is the same then append in a sub-list group like list B?

input

A = ['1070914_1070915_itemA',
     '1070915_1070921_itemA',
     '1070921_1070928_itemA',
     '1071005_1071008_itemA',
     '1071115_1071223_itemA',
     '1071223_1071224_itemA',
     '1071225_1071229_itemB']

outcome

B = [['1070914_1070915_itemA',
      '1070915_1070921_itemA',
      '1070921_1070928_itemA'],
     ['1071005_1071008_itemA'],
     ['1071115_1071223_itemA',
      '1071223_1071224_itemA'],
     ['1071225_1071229_itemB']
    ]
1 Answers

Here is the solution based on the example you shared where I am assuming:

  • Your time series list is already sorted based on start and end time
  • No two elements in the list overlap the start/end time window

Here is the sample code to achieve this:

my_list = [
    '1070914_1070915_itemA',
    '1070915_1070921_itemA',
    '1070921_1070928_itemA',
    '1071005_1071008_itemA',
    '1071115_1071223_itemA',
    '1071223_1071224_itemA',
    '1071225_1071229_itemB'
]

new_list = [[my_list[0]]]

for a, b in zip(my_list, my_list[1:]):
    a_tup, b_tup = a.split('_'), b.split('_')
    if a_tup[1] != b_tup[0]:
        new_list.append([])
    new_list[-1].append(b)

where new_list will return you:

[[
    '1070914_1070915_itemA', 
    '1070915_1070921_itemA', 
    '1070921_1070928_itemA'
 ],[
    '1071005_1071008_itemA'
 ],[
    '1071115_1071223_itemA', 
    '1071223_1071224_itemA'
 ],[
    '1071225_1071229_itemB'
 ]]
Related