Given (any) list of words lst
I should divide it into 10 equal parts.
x = len(lst)/10
how to give these parts variable names?
In the output I need 10 variables (part1, part2... part10
) with x
number of words in it.
Given (any) list of words lst
I should divide it into 10 equal parts.
x = len(lst)/10
how to give these parts variable names?
In the output I need 10 variables (part1, part2... part10
) with x
number of words in it.
To achieve the same result as Paulo's update (divide a list into n chunks with size only differing by 1), the following is an elegant solution using recursion.
Example:
I'll write this code so you learn the technique, but you shouldn't do this. The point of container datatypes like
list
andset
is that you can have arbitrary contents without having to make variables for each elements. So,Don't do this
(The
chunks
recipe is from Ned Batchelder's answer in the linked question. The reason you shouldn't do this is that modifyinglocals
(or indeedglobals
orvars
) is not good practice: it causes hard-to-determine behaviour and possibly very nasty bugs.Use tuple/list a result - the most reasonable approach
If you need to define new variables, you can
setattr
and add new attributes to anyobject
. It is safe since you won't overwrite existing variables:locals()
orglobals()
dictionary depending on the context your code is running in.Seen several solutions, but couldn't help post mine:
Can probably be summarized further, of course, but I think this way it is clear to read.
One-liner returning a list of lists, given a list and the chunk size:
Testing:
Update:
Well, in this case, you can try:
I'm sure this can be improved but I'm feeling lazy. :-)
See this question for how to generate equal chunks of a list. Then, if you really need them in separate variables, you can do:
But I would recommend making the code more general, instead of hardcoding it to 10 parts.