列表常遇到的几个问题:
1、列表元素有非数字的字符串
2、列表元素有数字为字符串类型
如何将列表元素为""的替换为0,列表字符转换为数值可用以下三种方法:循环、列表生成式、numpy(推荐)
二维数组建议用Numpy
num_list =['13', '', '', '', '6', '0']
l=[]
for i in num_list:
if i =="":
l.append(0)
else:
l.append(i)
num_list =['13', '', '', '', '6', '0']
new_list = [0 if i =="" else i for i in num_list]
new_list
num_list_new = list(map(lambda x : int(x),new_list))
对于numpy一维二维操作都一样
import numpy as np
s=['13', '', '', '', '6', '0']
a = np.array(s)
a[a==""]=0
输出
['13' '0' '0' '0' '6' '0']
a =list( a.astype("int")) # 或a.astype( np.uint8 )
# 或a = a.astype("int").tolist()
输出
[13, 0, 0, 0, 6, 0]
import numpy as np
s=[['4', '4', '1', '0', '25', '0'], ['13', '', '', '', '6', '0'], ['4', '2', '0', '', '17', '1']]
a = np.array(s)
a[a==""]=0
输出
[['4' '4' '1' '0' '25' '0']
['13' '0' '0' '0' '6' '0']
['4' '2' '0' '0' '17' '1']]
s=[['4', '4', '1', '0', '25', '0'], ['13', '', '', '', '6', '0'], ['4', '2', '0', '', '17', '1']]
a = np.array(s)
a[a==""]=0
a =a.astype("int").tolist() # a.astype( np.uint8 )
输出
[[4, 4, 1, 0, 25, 0], [13, 0, 0, 0, 6, 0], [4, 2, 0, 0, 17, 1]]