简体   繁体   English

如何使用 python 中的另一个列表创建可变大小的列表列表?

[英]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.假设我将从用户那里获得一个包含 n 行和 j 列的列表。 Then, I will have nxj sized list in my database.然后,我将在我的数据库中有 nxj 大小的列表。

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.它可以是任何大小,因为我的代码会将其转换为 1 行和 k 列大小的列表。

I want to append the second list to the nxj list by converting the second list column number to j.我想通过将第二个列表列号转换为 j 来将第二个列表 append 转换为 nxj 列表。

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:用户发送了第二个列表,我的代码将其转换为 1 xn 大小的列表:

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.问题是将第二个列表转换为列表的配对列表,其中每个内部列表都是first_list_column_number大小。 The first_list_column_number should stay there due to the scalability of the code.由于代码的可伸缩性, first_list_column_number应该保留在那里。

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 .有很多方法可以使用或不使用numpy在任何情况下,这里使用np.array_split() , arrays 的数量等于list2的长度除以list1的最后一个元素的长度。 Every array that results is converted to a list and used to extend list .结果的每个数组都将转换为列表并用于扩展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 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.如果你想避免任何导入(我讨厌它有时也很迟钝),你可以使用一些简洁的 python 技巧让它完全按照你的意愿行事。 Id advise looking around some python libraries others have posted on github to find some useful tricks.我建议查看一些 python 库,其他人在 github 上发布了一些有用的技巧。 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:这个 python 代码应该是您开始的良好基础:

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.我已经在我的 vscode 解释器中使用 python 3.7.6 运行它,所以它应该是功能齐全的并产生我给出的 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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