简体   繁体   中英

How to create variable sized list of lists using another list in python?

I know the title looks odd but I am going to explain it.

Say I will obtain a list from the user with n number of rows and j number of columns. Then, I will have nxj sized list in my database.

I will ask for another list from the user. It can be any size because my code will convert it to a 1 row and k column sized list.

I want to append the second list to the nxj list by converting the second list column number to j.

For example, the user sent the first list as below:

list1 = [[Column1, Column2], [1 , 2], [3 , 4]]

And the user sent the second list, and my code converted it to 1 xn sized list:

list2 = [5 , 6 , 7 , 8 , 9 , 10]

What I want is:

list1 = [[Column1, Column2], [1 , 2], [3 , 4], [5 , 6], [7 , 8], [9 , 10]]

My code perfectly finds the column number of the first list. The problem is converting the second list to paired list of lists in which every internal list is first_list_column_number sized. The first_list_column_number should stay there due to the scalability of the code.

I tried below method but it is not working and I couldn't find any help from the sources.

for i in range(len(list2)):
   for j in range(first_list_column_number)
       list1.append(list2[j])

But it only creates the same integers repeating. It is also not creating list of lists as I wanted.

Any help is appreciated.

There would be plenty of ways to do this with or without numpy In any case here's using np.array_split() with the number of arrays being equal to the length of list2 divided by the length of the last element of list1 . Every array that results is converted to a list and used to extend list .

import numpy as np
list1 = [['Column1', 'Column2'], [1 , 2], [3 , 4]]
list2 = [5 , 6 , 7 , 8 , 9 , 10]
list1.extend(map(list,np.array_split(list2,len(list2)/len(list1[-1]))))

print(list1)

Output

[['Column1', 'Column2'], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

If you want to avoid any imports (I hate how obtuse it can be sometimes too) you can use a couple neat python tricks to make it do exactly what you want. Id advise looking around some python libraries others have posted on github to find some useful tricks. My method also includes a feature that will pad columns if there were not enough items given in the second list. This python code should be a good base for you to start with:

list1 = [['Column1', 'Column2'], [1 , 2], [3 , 4]]
list2 = [5 , 6 , 7 , 8 , 9 , 10]
list3 = [5 , 6 , 7 , 8 , 9 , 10,11]

goal = [['Column1', 'Column2'], [1 , 2], [3 , 4], [5 , 6], [7 , 8], [9 , 10]]

print(  f'list1 = {list1}', 
        f'list2 = {list2}', 
        f'list3 = {list3}', 
        f'Goal:{goal}'      ,'\n', sep='\n')


def formatList(list1:list, list2:list):
    columnCount = len(list1[0])
    listBuffer = []
    #Groups items up and appends them to the first list
    for i in range(len(list2)):
        listBuffer.append(list2[i])
        if len(listBuffer) == columnCount:
            list1.append(listBuffer)
            listBuffer = []
    #Checks for excess items and padds them to make n colums
    if len(listBuffer) > 0:
        #This produces a list of None repeating x amount of times ie:[None,]*3 == [None,None,None]
        #It then appends that list to the buffer list and then appends the buffer to the first list
        listBuffer += [None,]*(columnCount-len(listBuffer))
        list1.append(listBuffer)
    return list1

print('Result using List1 and list2:',
        f'   {list1}  \n+  {list2}  = ',
        f'=  {formatList(list1.copy(), list2.copy())}', '\n', sep='\n')

print('Result using List1 and list3:',
        f'   {list1}  \n+  {list2}  ',
        f'=  {formatList(list1.copy(), list3.copy())}', '\n', sep='\n')



output="""
list1 = [['Column1', 'Column2'], [1, 2], [3, 4]]
list2 = [5, 6, 7, 8, 9, 10]
list3 = [5, 6, 7, 8, 9, 10, 11]
Goal:[['Column1', 'Column2'], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]


Result using List1 and list2:
   [['Column1', 'Column2'], [1, 2], [3, 4]]  
+  [5, 6, 7, 8, 9, 10]  = 
=  [['Column1', 'Column2'], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]


Result using List1 and list3:
   [['Column1', 'Column2'], [1, 2], [3, 4]]  
+  [5, 6, 7, 8, 9, 10]  
=  [['Column1', 'Column2'], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, None]]
"""

I have run this in my vscode interpreter with python 3.7.6 so it should be fully functional and produce the output i have given.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM