Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: creating list from string [duplicate]

I have list of strings

a = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']

I would like to create a list

b = [['word1',23,12],['word2', 10, 19],['word3', 11, 15]]

Is this a easy way to do this?

like image 524
Zenvega Avatar asked Oct 02 '11 18:10

Zenvega


2 Answers

input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
    items = item.split(',')
    output.append([items[0], int(items[1]), int(items[2])])
like image 106
David Heffernan Avatar answered Sep 22 '22 19:09

David Heffernan


Try this:

b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]
like image 33
user Avatar answered Sep 24 '22 19:09

user