Home > Enterprise >  Adding items to nested lists
Adding items to nested lists

Time:10-25

I am new to python and struggling with adding values to nested lists. I have a list that contains 6 values. My lists of lists contains 3 lists and I would like to add the values the 6 values in such a way that the 1 value goes to the 1 list, 2 value to 2nd list, 3rd value to 3 list. Then I would like to continue looping so that the 4 value goes to the first list, 5 value to second list and 6 value to 3rd list. In the end I want to end up with a list of three lists which each contains 2 items. I am struggling to get anything wise to run. Can someone help me on this, thank you!

CodePudding user response:

You can use the position of the item in the list of values (modulo the total number of target lists) to get the right list to append to.

lists = [[], [], []]                                                    
values = [1, 2, 3, 4, 5, 6]                                             
for i, x in enumerate(values): 
     lists[i % len(lists)].append(x) 

Or use itertools.cycle and zip:

from itertools import cycle                                            
lists = [[], [], []]                                                   
values = [1, 2, 3, 4, 5, 6]                                            
for x, l in zip(values, cycle(lists)): 
    l.append(x) 

Both ways, lists ends up as [[1, 4], [2, 5], [3, 6]].


In case you want more "regular" loops, you can also use range with start, stop and step parameters to create the sublists and then add those to the list of lists:

n = 3
lists = []
values = [1, 2, 3, 4, 5, 6]                                             
for k in range(n):
    lst = []
    for i in range(k, len(values), n):
        lst.append(values[i])
    lists.append(lst)

The same also works in a quite readable one-list list copmrehension:

lists = [[values[i] for i in range(k, len(values), 3)] for k in range(3)]

Or using zip, map and iter, in case you want to show off:

lists = list(map(list, zip(*zip(*[iter(values)]*3))))

CodePudding user response:

# list with 6 items
# each item in the list has an index/position;

#          0         1       2         3        4      5
cars = ['Subaru', 'Audi', 'Honda', 'Toyota', 'BMW', 'Mazda']

# two empty lists

first_3 = [] # for first 3 items of the "cars" list
last_3 = [] # for last 3 items of the "cars" list


#          0   1  2
finallist=[[],[],[]] # a list with three empty lists inside a list


for car in cars:
    # if the index/position of the car in the "cars" list is below 3
    # add the car to the end of the "first_3" list
    
    if cars.index(car) < 3:
          first_3.append(car)
          
    # if the index/position of the car in the "cars" list is above 2
    # add the car to the end of the "last_3" list
    
    if cars.index(car) > 2:
          last_3.append(car)


# loop the cars in the "first_3" list

for car in first_3:
    
    # get the index of the car in that list
    car_pos = first_3.index(car)
    
    # reference the list with the index "car_pos"
    # i.e - if car_pos is 2, that would be the last list inside of "finallist"
    
    finallist[car_pos].append(car) # append the car
    
    
# loop the cars in the "last_3" list and do the same thing
for car in last_3:
    car_pos = last_3.index(car)
    finallist[car_pos].append(car)


# print the final list
print(finallist)
  • Related