EarthIsHome
EarthIsHome

Reputation: 735

Break list up into sublists given a desired list size in python

I have a list that looks like this:

arr = [['3'], ['1', '0.0'], ['2', '0.05'], ['3', '0.1'], ['1', '1'], ['2', '1'], ['3', '1']]

I would like to break this list up into smaller sublists that are of the size given in the first element of the original list (e.g. 3 here) and only consist of the second element. What is the most pythonic way of doing this?

sublist1 = [0.0, 0.05, 0.1]
sublist2 = [1, 1, 1]

I've tried to use list comprehension, but I don't know how to prescribe the for loop to loop through the array (i.e. between indices 1 and 3 or between indices 4 and 6 in the example arr above).

n_nodes = arr[0][0] # gets number of nodes, 3
first_section = [element[1] for element in arr]

Upvotes: 1

Views: 79

Answers (3)

Joe Iddon
Joe Iddon

Reputation: 20414

A working list-comprehension:

[[e[1] for e in arr[i+1:i+int(arr[0][0])+1]] for i in range(0, len(arr)-1, int(arr[0][0]))]
#[['0.0', '0.05', '0.1'], ['1', '1', '1']]

Upvotes: 1

leotrubach
leotrubach

Reputation: 1597

Use list.pop() to get first element and convert it to integer. After that use slicing.

arr = [['3'], ['1', '0.0'], ['2', '0.05'], ['3', '0.1'], ['1', '1'], ['2', '1'], ['3', '1']]


size = int(arr.pop(0)[0])


l = [o[1] for o in arr]
res = [l[size*i:size*(i+1)] for i in range(len(l) // 3)]

print(res)

Upvotes: 1

wim
wim

Reputation: 362716

Let's break it into simple steps. First, get the chunk size as an integer:

>>> [n] = arr[0]
>>> n = int(n)
>>> n
3

Then, get a list of the second elements. There are several ways to do this, but the most readable is using a list comprehension:

>>> bs = [b for [a,b] in arr[1:]]
>>> bs
['0.0', '0.05', '0.1', '1', '1', '1']

Now, slice this list into chunks. That is an already solved problem, discussed ad infinitum here:

How do you split a list into evenly sized chunks?

Upvotes: 3

Related Questions