Chris
Chris

Reputation: 5834

How to split string at index[0] of each sublist, and have each split index in it's own original list?

How could you split a string at index 0 of all sublists into separate elements, and have each of the split elements be contained within a copy of the original sublist?

For example:

Original_List = [['a,b','c','d','e','f'],['1','2','3'],['z,y','1','2']]

Desired Result:

Desired_List = [['a','c','d','e','f'],['b','c','d','e','f'],['1','2','3'],['z','1','2'],['y','1','2']]

Also, to add further clarity with one more actual example:

Original_List = [['Contract_ID1,Contract_ID2','Amount','Date'],['Contract_ID3,Contract_ID4','400','Jan1']]

I want every sublist to have only one Contract_ID, but still have the Amount and Date Associated with it

Desired_List =  [['Contract_ID1','Amount','Date'],['Contract_ID2','Amount','Date'],['Contract_ID3','400','Jan1'],['Contract_ID4','400','Jan1']]

I can split all strings at index 0 of all sublists with the below, but I can't figure out how I would duplicate the whole list for each split element and then replace the strings that were split with the split element, so that each split element had its own list.

Split_First_Indices_of_Sublists = map(lambda x: x[0].split(","),Original_List)
>>[['a', 'b'], ['1'], ['z', 'y']]
for x in Original_List:
     x.pop(0)
>> [['c', 'd', 'e', 'f'], ['2', '3'], ['1', 2]]

Upvotes: 1

Views: 483

Answers (2)

shiny
shiny

Reputation: 124

Original_List=[['a,b','c','d','e','f'],['1','2','3'],['z,y','1','2']]
desired_list=[]
for p in pl:
    try:
        splited=p.split(',')
        if not type(splited) is list:
            splited=[splited]
        if count(splited)>1:
            for list in splited:
                p[0]=list
                desired_list.append(p)
        else:
            desired_list.append()
    except:
        pass

Upvotes: 0

roippi
roippi

Reputation: 25974

I think it's clearest written out as explicit loops:

Desired_List = []

for li in Original_List:
    for spl in li[0].split(','):
        Desired_List.append([spl] + li[1:])

gives:

Desired_List
Out[153]: 
[['a', 'c', 'd', 'e', 'f'],
 ['b', 'c', 'd', 'e', 'f'],
 ['1', '2', '3'],
 ['z', '1', '2'],
 ['y', '1', '2']]

And of course you can immediately turn this into the equivalent one-line list comp:

[[spl] + li[1:] for li in Original_List for spl in li[0].split(',')]

Which may or may not be less readable, depending on the reader :-)

And as a last note, make sure that this is the data structure you really want. A dict keyed by Contract_ID seems like a very natural structure for your end product.

Upvotes: 3

Related Questions