Wednesday, July 20, 2022

[FIXED] How to convert numeric string from a sublist in Python

Issue

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

Solution

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)


Answered By - Ajeigbe Oladayo
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.