2

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']
    ]
2
  • 1
    can you add the rule which you're following to group them ? Commented May 2, 2021 at 8:08
  • i think it would help to first separate these strings into items with .split("_") Commented May 2, 2021 at 8:08

1 Answer 1

1

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'
 ]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing such a solution. Help a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.