Search code examples
pythonlistappendsublist

Splitting a huge list into smaller lists and append items to those sublists


I have a huge list that was imported from a csv file. This list has over 40,000 string elements. I want to divide each element into an independent list.

This an extract from my list:

['090-102  XX.Abcdefg;Female;95 y más años;1985;24\n',
 '090-102  XX.Abcdefg;Female;95 y más años;1984;52\n', 
 '090-102  XX.Abcdefg;Female;95 y más años;1983;60\n', 
 '090-102  XX.Abcdefg;Female;95 y más años;1982;61\n', 
 '090-102  XX.Abcdefg;Female;95 y más años;1981;63\n', 
 '090-102  XX.Abcdefg;Female;95 y más años;1980;48\n']

I want each item in the list to be separated into a new list like this:

[['090-102  XX.Abcdefg,Female,95 y más años,1985,24\n']
 ['090-102  XX.Abcdefg,Female,95 y más años,1984,52\n'] 
 ['090-102  XX.Abcdefg,Female,95 y más años,1983,60\n'] 
 ['090-102  XX.Abcdefg,Female,95 y más años,1982,61\n'] 
 ['090-102  XX.Abcdefg,Female,95 y más años,1981,63\n'] 
 ['090-102  XX.Abcdefg,Female,95 y más años,1980,48\n']]

And I also have to insert new elements (elements from two other lists) into the new separated sublists:

other_list = ['XX','XX','XX','XX','XX','XX']
other_list2 = [20, 20, 20, 20, 20, 20]

So my final output looks like this:

[['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n']
 ['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n']
 ['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n'] 
 ['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n'] 
 ['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n']
 ['090-102  XX', 'XX', 20, 'Abcdefg,Female,95 y más años, 1985, 24\n']]

I don't know if I should append the items first into the huge list, before separating it into sublists. Any help will be greatly appreciated.


Solution

  • I am assuming all your lists are of the same length, otherwise, you have to fill the gaps first. I see you are trying to create a new list out of 3 (or more) lists and the new list has the same format to all of its elements. You might first split the items from your first list on the dots by:

    newList1=[]
    for i in list11:
       newList1.append(i.split('.')) 
    

    this will convert each element of your list to a list where the first item is whatever before the dot and the second item is whatever after the dot. Then adds this list the newList1 variable.

    after that, it is a simple for loop:

    a = [['xx','xx'], ['yy', 'yy'] , [ 'zz', 'zz']]
    b = [1,2,3]
    c = [0, 00, 000]
    newList2 = []
    for i in range(len(a)):
        newList2.append(a[i][0]+str(b[i])+a[i][1]+str(c[i])) #adjust to your format