[Python] how to create uniform nested lists and convert them in to multi dimensional arrays?

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    i would like to create a nested list of arbitrary depth (containing numerical values specifically) with uniform arbitrary lengths at each level and then compress it to a NumPy array of minimum dimensions ie. if a layer of lists all length 1 all lists at that depth are unpacked.

    example:


    import random as ran
    import numpy as np

    prompt = (3,1,5,1)
    #promt length and positions of 1 should be arbitrarily
    old_list = []

    for a in range(prompt[0]):
    old_list.append([])
    for b in range(prompt[1]):
    old_list[a].append([])
    for c in range(prompt[2]):
    old_list[a].append([])
    for d in range(prompt[3]):
    #using random outputs for simplicity, could be anything
    old_list[a][c].append(ran.randint(0, 10))

    new_list = []
    for a in range(prompt[0]):
    new_list.append([])
    #prompt[1] should be automatically skipped as it is 1
    for c in range(prompt[2]):
    #prompt[3] should be automatically skipped as it is 1
    new_list[a].append(old_list[a][0][c][0])
    final = np.array(new_list)

    print(f'''{final}
    is clearly and more useful and tidier than
    {old_list} ''')


    I expect there is some way of automating for loops in the manner described, and compacting them as well, in NumPy, but I don't Know where to get started. any help would be apreciated. thankyou!

    Continue reading...

Compartilhe esta Página