Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting list of lists of strings into integer in Python

I want to convert the string elements to integers within the each following list:

old = [['29,1,22,14,32,11,11,3'],
 ['2,3,1,2,1,4,1,1,3,1'],
 ['5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7'],
 ['2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2'],
 ['29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5']]

I have tried the following codes:

[[int(num) for num in sub] for sub in old]
[list(map(int, sublist)) for sublist in old]

These are not working in my case. I need the following outputs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new = [[29,1,22,14,32,11,11,3],
 [2,3,1,2,1,4,1,1,3,1],
 [5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7],
 [2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2],
 [29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5]]

>Solution :

Try:

old = [['29,1,22,14,32,11,11,3'],
 ['2,3,1,2,1,4,1,1,3,1'],
 ['5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7'],
 ['2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2'],
 ['29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5']]

new = [[int(x) for x in sublst[0].split(',')] for sublst in old]
# new = [list(map(int, sublst[0].split(','))) for sublst in old] # an alternative

print(new)
# [[29, 1, 22, 14, 32, 11, 11, 3], [2, 3, 1, 2, 1, 4, 1, 1, 3, 1], [5, 2, 1, 1, 3, 1, 2, 4, 1, 1, 2, 2, 2, 1, 19, 2, 1, 7], [2, 2, 1, 5, 6, 1, 2, 3, 9, 2, 1, 1, 2, 6, 1, 1, 2, 3, 1, 1, 2], [29, 44, 5, 8, 17, 20, 26, 47, 80, 29, 47, 17, 23, 26, 46, 69, 8, 2, 5, 38, 8, 5, 5]]

You need to use split to parse each long string into small strings, and then apply int to convert a string into an int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading