2

Given a number I want to split it separate but even-ish list which I can do :

import numpy as np
pages = 7
threads = 3
list_of_pages = range(1,pages+1)
page_list = [*np.array_split(list_of_pages, threads)]

Returns:

[array([1, 2, 3]), array([4, 5]), array([6, 7])]

I would like it to return a list of lists instead, ie:

[[1,2,3],[4,5],[6,7]]

I was hoping to do something like this (below doesnt work):

page_list = np.array[*np.array_split(list_of_pages, threads)].tolist()

is that possible or do I need to just loop through and convert it?

4
  • use list comprehension [x.tolist() for x in np.array_split(list_of_pages, threads)] Commented Oct 2, 2019 at 5:33
  • If you don't want arrays, you probably shouldn't be using NumPy. Commented Oct 2, 2019 at 5:37
  • 1
    I think he wants to utilize np.array_split to evenly split the list. @user2357112 Commented Oct 2, 2019 at 5:40
  • 1
    @zihaozhihao: Yeah, but they still probably shouldn't be using NumPy to do it. It's a pretty heavy dependency to pull in just for this, and things like automatic dtype conversion make it easy to screw things up if you're using NumPy for list manipulation. For example, numpy.array_split([1, 1.0, '1'], 2) converts the numbers to strings. Commented Oct 2, 2019 at 5:55

2 Answers 2

4

Assuming page_list is a list of ndarray, then you can convert to python list like this,

[x.tolist() for x in [*page_list]]
# [[1, 2, 3], [4, 5], [6, 7]]
Sign up to request clarification or add additional context in comments.

Comments

1

@zihaozhihao gave a inline solution. You can also write a for loop to iterate over every item in page_list and convert it to list

list_of_lists = [ ]

    for x in [*page_list]]:
        list_of_lists.append(x.tolist())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.