0

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
2
  • [[int(i) if i.isdecimal() else i for i in l] for l in list_samp] Commented Jan 11, 2022 at 10:39
  • Your inner loop seems completely unnecessary, you are not even using element anywhere inside it. Do you want to convert the first element to int or all elements that can be converted? Commented Jan 11, 2022 at 10:40

3 Answers 3

0

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.