开发者

Python - splitting a list into a known number of lists with a numeric name

开发者 https://www.devze.com 2023-04-06 16:44 出处:网络
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

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 num开发者_Go百科bers.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消