Reputation:
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:
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]
Upvotes: 0
Views: 86
Reputation: 427
If you have mixture of text and number, this would be the best solution
Because string can appear at any location
wholeList = [ ['apple','1','2'],['2','banana', '3'],['3','4', 'cherry'],['downypitch', '4','5'] ]
newlist = []
for sublist in wholeList:
temp = []
for string in sublist:
try:
temp.append(int(string))
except:
temp.append(string)
newlist.append(temp)
print(newlist)
# op: wholeList = [ ['apple','1','2'],['2','banana', '3'],['3','4', 'cherry'],['downypitch', '4','5'] ]
Upvotes: 0
Reputation: 26998
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]]
Upvotes: 0
Reputation: 13939
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]]
Upvotes: 0