11

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?

0

5 Answers 5

28
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])]) 
Sign up to request clarification or add additional context in comments.

3 Comments

@Oliver I'm not sure if you are being serious or not! ;-) Doesn't seem all that Pythonic. List comprehensions have their place but they can be overdone in my view. Or perhaps that's just my lack of familiarity with them.
Definitely serious! It's very readable. I think this is a classic example where list comprehensions can be used, but in the end are not the best way to go.
It's a matter of style I guess, I much prefer the list comprehension!
8

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)) ] 

Comments

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] 

Comments

1

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.

Comments

1

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(', ')] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.