newbieprogrammer
newbieprogrammer

Reputation: 19

Converting list of list of strings into list of list of integers

listX = [['0,0,0,3,0,4,0,3'], ['0,0,0,0,0,3,0,7'], ['0,0,1,0,0,5,0,4'], ['0,0,0,1,3,1,0,5'], ['1,1,1,0,0,0,2,5'], ['0,0,0,1,1,5,0,3'], ['0,0,0,5,3,0,0,2']]

I need it to output

[[0, 0, 0, 3, 0, 4, 0, 3], [0, 0, 0, 0, 0, 3, 0, 7], [0, 0, 1, 0, 0, 5, 0, 4], [0, 0, 0, 1, 3, 1, 0, 5], [1, 1, 1, 0, 0, 0, 2, 5], [0, 0, 0, 1, 1, 5, 0, 3], [0, 0, 0, 5, 3, 0, 0, 2]]

when I use listX = [[int(float(o)) for o in p] for p in listX] I get ValueError: could not convert string to float: '0,0,0,3,0,4,0,3'

Upvotes: 2

Views: 64

Answers (5)

scionx
scionx

Reputation: 167

My in-place solution:

listX = list(map(lambda x: list(int(y) for y in x[0].split(',')), listX))

Upvotes: 0

shadowmordor
shadowmordor

Reputation: 1

Given your input is

[['0,0,0,3,0,4,0,3'], ['0,0,0,0,0,3,0,7'], 
 ['0,0,1,0,0,5,0,4'], ['0,0,0,1,3,1,0,5'], 
 ['1,1,1,0,0,0,2,5'], ['0,0,0,1,1,5,0,3'], 
 ['0,0,0,5,3,0,0,2']]

Let us start off by splitting it at , using the split method and dumping the whole content into a temporary array say x. The code is as follows-

x=[]
[[x.append(j.split(",")) for j in i] for i in input]
print(x)

The print(x) statement is used solely for debugging & understanding how that part of my code works. You can remove it as seen fit. Now we perform the conversion of lists of strings to lists of integers and store it in the variable say 'y'. The code is as follows -

y = [[int(j) for j in i] for i in x]
print(y)

Upvotes: 0

Steve
Steve

Reputation: 54392

If you have a list of lists with more than a single item you could try the following (nested) list comprehension:

output = [list(map(int, y.split(','))) for x in listX for y in x]

If know your lists contain only a single item, all you'll need is:

output = [list(map(int, x[0].split(','))) for x in listX]

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520988

You may try the following list comprehension:

output = [[int(x) for x in re.findall(r'\d+', y[0])] for y in listX]
print(output)

This prints:

[[0, 0, 0, 3, 0, 4, 0, 3], [0, 0, 0, 0, 0, 3, 0, 7],
 [0, 0, 1, 0, 0, 5, 0, 4], [0, 0, 0, 1, 3, 1, 0, 5],
 [1, 1, 1, 0, 0, 0, 2, 5], [0, 0, 0, 1, 1, 5, 0, 3],
 [0, 0, 0, 5, 3, 0, 0, 2]]

This uses a nested list comprehension. The outer comprehension feeds one-element CSV integer strings into the inner comprehension. The inner list comprehension uses re.findall to find integers inside the CSV list, one at a time.

Upvotes: 1

azerELweed
azerELweed

Reputation: 115

You need to firs split every string you have listX[i].split(",") and then apply the casting

Upvotes: 1

Related Questions