this question is to convert selected strings in the list into integers.
However, this code converts the whole list into integer. how can i fix this?
list = [['x', 'x', '1', 'x'], ['4', 'x', 'x', 'x'], ['x', 'x', 'x', '2'], ['x', '3', 'x', 'x']]
def convert(str_list):
for i in range(len(str_list)):
for j in range(len(str_list)):
if str_list[i][j].isdigit():
str_list[i][j] = int(str_list[i][j])
return(str_list)
edit: this code ^above also works. i edited it already!! The output should be
[['x', 'x', 1, 'x'], [4, 'x', 'x', 'x'], ['x', 'x', 'x', 2], ['x', 3, 'x', 'x']]
map
this function to your list:
def str2num(s):
# Convert a string to an int, float, or stripped string
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return s.strip()
You can check if a string contains digits with .isdigit()
. So you can call int
only if the element at that index contains digits:
def convert(str_list):
n = 0
while n < len(str_list):
if str_list[n].isdigit():
str_list[n] = int(str_list[n])
n += 1
return(str_list)
You can then loop over all lists in your main list and convert them individually:
lst = [['x', 'x', '1', 'x'], ['4', 'x', 'x', 'x'], ['x', 'x', 'x', '2'], ['x', '3', 'x', 'x']]
for l in lst:
convert(l)
print(lst)
Output
[['x', 'x', 1, 'x'], [4, 'x', 'x', 'x'], ['x', 'x', 'x', 2], ['x', 3, 'x', 'x']]
A list comprehension would be perfect for this, (also don't overwrite builtins!)
data = [['x', 'x', '1', 'x'], ['4', 'x', 'x', 'x'], ['x', 'x', 'x', '2'], ['x', '3', 'x', 'x']]
def converted(str_list):
return [int(s) if s.isdigit() else s for s in data]
If you must use a while loop you can do this:
def convert(str_list):
for i in range(len(data)):
for n in range(len(data[i])):
try: data[i][n] = int(data[i][n])
except: pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.