[英]how to convert selected string in list to integer python
这个问题是将列表中选定的字符串转换为整数。
但是,此代码将整个列表转换为 integer。 我怎样才能解决这个问题?
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)
编辑:此代码 ^ 上面也有效。 我已经编辑过了!! output 应该是
[['x', 'x', 1, 'x'], [4, 'x', 'x', 'x'], ['x', 'x', 'x', 2], [ 'x', 3, 'x', 'x']]
map
这个 function 到你的名单:
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()
您可以使用.isdigit()
检查字符串是否包含数字。 因此,只有当该索引处的元素包含数字时,您才能调用int
:
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)
然后,您可以遍历主列表中的所有列表并单独转换它们:
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']]
列表理解将是完美的,(也不要覆盖内置!)
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]
如果你必须使用 while 循环,你可以这样做:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.