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

(When list mix with text & numbers) How to convert numbers in each small list into numeric instead of string within that big list in python?

The list is mixed with both text and numbers. And so far they all have ‘ ‘ symbol, means they are all string? So how to convert numbers in each small list into numeric instead of string within that big list in python?

This is what I have:

wholeList = [ [‘apple’,’1′,’2′],[‘banana’,’2′,’3′],[‘cherry’, ‘3’,’4′],[‘downypitch’, ‘4’,’5′] ]

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

This is what I want:
text such as apple have type string, while the numbers such as 2 have type numeric

newList = [ [apple,1,2],[banana,2,3],[cherry, 3,4],[downypitch, 4,5]]

This is what I tried:

newList = []

for t in wholeList:
    num_part = t[1:]
    
    for j in num_part:
        new_part = int(j)
        newList.append(new_part)

print(newList)

However, this gives me something like this:

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

>Solution :

Based on your code, I am assuming that 0-th entry remains to be string, while 1st, 2nd, … are to be converted into integers.

You can use list comprehension as follows:

whole_list = [ ['apple','1','2'],['banana','2','3'],['cherry', '3','4'],['downypitch', '4','5'] ]

new_list = [[sublst[0], *map(int, sublst[1:])] for sublst in whole_list]
print(new_list) # [['apple', 1, 2], ['banana', 2, 3], ['cherry', 3, 4], ['downypitch', 4, 5]]
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