Home > Enterprise >  (When list mix with text & numbers) How to convert numbers in each small list into numeric instead o
(When list mix with text & numbers) How to convert numbers in each small list into numeric instead o

Time:03-12

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

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]

CodePudding user response:

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

CodePudding user response:

Here's an approach that allows for the number strings being anywhere in the sublists and for the sublists to be of any length:

wholeList = [ ['apple','1','2'],['banana','2','3'],['cherry', '3','4'],['downypitch', '4','5'] ]
newList = wholeList[:]
for e in newList:
    for i, x in enumerate(e):
        try:
            e[i] = int(e[i])
        except ValueError:
            pass
print(newList)

Output:

[['apple', 1, 2], ['banana', 2, 3], ['cherry', 3, 4], ['downypitch', 4, 5]]
  • Related