0

I'm working with python 2.5.1 . I have a list ('coll') with 122 values. I want to split it into 15 lists, where the first list will get the first nine values (coll[0-8]), and will be called 'coll_1', the second list will be called 'coll_2' and have values 9-17 and so on...

how do I do that?

EDIT: the values in the list are STRINGS, not numbers.

jonatr
  • 370
  • 1
  • 7
  • 19
  • 1
    what have you tried? BTW do some search on SO before posting, question has been answerd number of times. Best solution is probably this one http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python/312464#312464 – Fredrik Pihl Sep 20 '11 at 12:46
  • BTW, didn't intent for the comment above to sound so harsh, sorry and keep them posts coming. – Fredrik Pihl Sep 20 '11 at 12:55
  • There's two different aspects to this -- splitting the list (for which the question you forwarded does have a good solution), and injecting the names to the current scope, which, to be fair, the discussion there does not address (because it was not part of the question). – michel-slm Sep 20 '11 at 12:57
  • I tried several types of split I found while searching, I didn't succeed in 1. putting coll[x:y] and changing it in a for loop and 2. nameing the new lists coll1,coll2, coll2 in a generic way. – jonatr Sep 20 '11 at 12:57

3 Answers3

3

This is just asking for trouble. Why not just create a list of those lists?

colls = [coll[9*i:9*(i+1)] for i in range(15)]

This way you can access each of them without going through dynamic execution, local variables inspection, or things like that.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0

Use locals to get a dictionary of the local variables of the current scope, which you can then manipulate.

coll = range(100,222)
for i in range(15):
    locals()['coll_' + str(i+1)] = coll[9*i:(9*i)+8]

Note that you miscalculated; coll_14 is not full and coll_15 is empty

michel-slm
  • 9,438
  • 3
  • 32
  • 31
  • from the [python 2.5 documentation](http://docs.python.org/release/2.5/lib/built-in-funcs.html#l2h-47): "Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter." so, modifying `locals()` does not seem a good idea... – Adrien Plisson Sep 20 '11 at 12:58
  • Works for me on iPython and on Python (v2.7.1). – michel-slm Sep 20 '11 at 13:35
0
for i in range(len(coll)/9):
    exec 'coll_'+str(i+1)+'='+str(coll[i*9:(i+1)*9])

but using exec poses a great security risk if the content of coll comes from a user input.

Adrien Plisson
  • 22,486
  • 6
  • 42
  • 73