1

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]
EarthIsHome
  • 655
  • 6
  • 18

3 Answers3

3

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?

wim
  • 338,267
  • 99
  • 616
  • 750
1

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']]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

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)
leotrubach
  • 1,509
  • 12
  • 15