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?
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])]) 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 even more concise:
def parseClause(a,b,c): return [a, int(b), int(c)] b = [parseClause(*clause) for clause in a] If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. 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 longer than the other answers, but it's more versatile.
I know this is old but here's a one liner list comprehension:
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(', ')]