Python: creating a list from a string

I have a 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 an easy way to do this?

+7
source share
5 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])]) 
+22
source

Try the following:

 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)) ] 
+6
source

More concise than others:

 def parseString(string): try: return int(string) except ValueError: return string b = [[parseString(s) for s in clause.split(', ')] for clause in a] 

Alternatively, if your format is fixed as <string>, <int>, <int> , you can be more concise:

 def parseClause(a,b,c): return [a, int(b), int(c)] b = [parseClause(*clause) for clause in a] 
+2
source

If you need to convert some of them to numbers and not know in advance which of them will require additional codes. Try something like this:

 b = [] for x in a: temp = [] items = x.split(",") for item in items: try: n = int(item) except ValueError: temp.append(item) else: temp.append(n) b.append(temp) 

This is more than other answers, but it is more universal.

+1
source

I know this is old, but here is one understanding of the list of linear elements:

 data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15'] [[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data] 

or

 [int(item) if item.isdigit() else item for items in data for item in items.split(', ')] 
+1
source

All Articles