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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Zenvega
  • 1,974
  • 9
  • 28
  • 45

5 Answers5

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])])
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 3
    @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. – David Heffernan Oct 02 '11 at 18:57
  • 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. – user Oct 02 '11 at 20:33
  • It's a matter of style I guess, I much prefer the list comprehension! – wim Oct 02 '11 at 23:15
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)) ]
user
  • 7,123
  • 7
  • 48
  • 90
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]
ninjagecko
  • 88,546
  • 24
  • 137
  • 145
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(', ')]
Dan P.
  • 1,433
  • 1
  • 16
  • 28
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.

Javier
  • 4,552
  • 7
  • 36
  • 46