Python: Curious about making lists with dynamic variables.

Asked 2 years ago, Updated 2 years ago, 42 views

Hello, this is Corinne.

I want to implement one, but it doesn't work.

What I want to implement is

So the final goal is to split an arbitrary list into the number you enter, and to bind an automatically generated name to each of the split lists.

You can search for this and that and make a name automatically according to the number of split lists that match the number you entered.

3) I can't bind the name variable and the split list.

I want to study coding as a hobby, but it's too hard.

(I don't know if the title of the question I wrote is appropriate.)

Thank you for your advice.

listA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

n = 4

results = [listA[i*n:(i+1)*n] for i in range((len(listA) -1 + n) // n)]

def setName():

    names = []

    for i in range(len(results)):
        names.append("listA-" + str(i + 1))
    print(names)

#Blocked at the bottom.
    for name in names:
        globals()[name]  = results[]

#Normal operation below.
    for name in names:
        print(name, "=", globals()[name])

setName()

python list

2022-09-20 17:56

1 Answers

You're going to split up the list called A and make it into A_1, A_2, and A_3, right? You don't have to make a name like A_1. Just make a list of the lists, A_lists[0], A_lists[1], ... This is how you do it.

Here's an example below.

>>> l = list(range(50))
>>> n = 15
>>> lists = [ l[i*n:(i+1)*n] for i in range((len(l) + n -1) // n) ]
>>> lists
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, 47, 48, 49]]
>>> lists[0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> lists[1]
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>> def process_list(l_15):
    s = sum(l_15)
    return s

>>> for i, list_i in enumerate(lists):
    print(i, process_list(list_i))


0 105
1 330
2 555
3 235

You break up a 50-piece list, put it in a variable called lists, and when you approach each split list, lists[0], lists[1], ... This is how you use it.

OK?


2022-09-20 17:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.