-1

I have been trying to create sublists within lists so that I can call on the sum function to have all the value (each sublists must have the same length). I tried using the range function with having the start and end as variable, and after each variable, add up to the start and end.

temp1 = list()
distance = list()
start = 0
end = 3
distance_list = [1.4.5,5,3,5,4,5,8]
for a in range(3):
    for b in range(start,end):
        temp1.append(distance_list[b]
        distance.append(temp1)
        start += 3
        end += 3

Here, the expected result is to simply be able to create a list that is like

distance = [[1,4,5],[5,3,5],[4,5,8]]

However, the result that I got is the fact that the number b got extremely large. What are some suggestion to tackle this problem?

2 Answers2

1
dis = [1,4,5,5,3,5,4,5,8]

sol = [dis[i:i+3] for i in range(0,len(dis),3)]

print(sol)

output

[[1, 4, 5], [5, 3, 5], [4, 5, 8]]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

This should solve the purpose

def split_list_to_multiple(input_vals, num_of_splits=5):
    """Splits a list into given number of splits, lists."""
    k, m = divmod(len(input_vals), num_of_splits)
    return (input_vals[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(num_of_splits))