Home > Blockchain >  Python list append automation [closed]
Python list append automation [closed]

Time:09-25

I am looking to append i to list1 then list2 then list 3 and so on, I am using python

        for person in population_list: 
            counter = 0
            place = random.randint(1, 5)
            if person:
                while counter <= places:
                    if place == counter:
                        place{counter}.append(person)
            else:
                pass

CodePudding user response:

Don't append the elements one by one, this is inefficient, just do copies:

main_list = ["a", "b", "c"]
list1 = main_list.copy()
list2 = main_list.copy()
list3 = main_list.copy()

If you can, use containers, this makes life easier:

lists = [main_list.copy() for _ in range(3)]

then access:

list[0]
list[1]
list[2]

edit: assign elements of a list to random buckets

population_list = list('ABCDEFGHIJKLMNOP')
places = {i: [] for i in range(1,6)}
for p in population_list:
    places[random.randint(1, 5)].append(p)
places

example output:

>>> places
{1: ['B', 'C', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'P'],
 2: ['A', 'N'],
 3: ['D'],
 4: ['I', 'O'],
 5: ['E']}

>>> places[2]
['A', 'N']

CodePudding user response:

Then just loop over the lists:

main_list = ["a", "b", "c"]
list1,list2,list3 = [], [], []

for list in [list1,list2,list3]:
    list.extend(main_list)
  • Related