glowbt
glowbt

Reputation: 3

How to convert numeric string from a sublist in Python

I'm a freshie. I would like to convert a numeric string into int from a sublist in Python. But not getting accurate results. 😔

countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]

for list in list_samp:
  countitem =+1
  for element in list:
    convert_element = int(list_samp[countitem][0])
    list_samp[countitem][1] = convert_element

Upvotes: 0

Views: 39

Answers (3)

Jessej Samuel
Jessej Samuel

Reputation: 71

Let's go through the process step-by-step

countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]

#Let's traverse through the list
for list in list_samp:  #gives each list
  for i in range(len(list)): # get index of each element in sub list
    if list[i].isnumeric(): # Check if all characters in the string is a number
      list[i] = int(list[i]) # store the converted integer in the index i

Upvotes: 0

Tal Folkman
Tal Folkman

Reputation: 2571

The correct way to do it:

list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
list_int = [[int(i) if i.isdecimal() else i for i in l] for l in list_samp]
print(list_int)

Upvotes: 0

Babatunde Mustapha
Babatunde Mustapha

Reputation: 2653

You can do it like this:

list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
me = [[int(u) if u.isdecimal() else u for u in v] for v in list_samp]
print(me)

Upvotes: 0

Related Questions