除了第一个值,我必须将嵌套列表中的值转换为整数。例如:
x = [['a', '1',' 2',' 3', '4',' 5'], ['b', '11',' 12',' 13',' 14',' 15'], ['c', '21',' 22',' 23',' 24', '25']]
对此
x = [[ 1, 2, 3, 4, 5], [ 11, 12, 13, 14, 15], [21, 22, 23, 24, 25]]
我尝试使用
w = []
for i in list1:
for j in i:
v = list(int(j))
w.append(v)
和
for i in file_list:
j = i[:1] + list(map(int, i[1:]))
但我知道
Traceback (most recent call last): File "/Users/abhishekabhishek/PycharmProjects/normalize/venv/normalize.py", line 63, in <module> v = list(int(j)) ValueError: invalid literal for int() with base 10: '2.66171813'
答案 0 :(得分:1)
检查字符串是否可以转换为数字的一种更可靠的方法是实际将其转换,但是使用try-except
块来捕获异常:
for i, l in enumerate(x):
r = []
for f in l:
try:
r.append(float(f))
except ValueError:
pass
x[i] = r
所以给定:
x = [['a', '1.1',' 2',' 3', '4',' 5'], ['b', '11',' 12',' 13',' 14',' 15'], ['c', '21',' 22',' 23',' 24', '25']]
x
将变为:
[[1.1, 2.0, 3.0, 4.0, 5.0], [11.0, 12.0, 13.0, 14.0, 15.0], [21.0, 22.0, 23.0, 24.0, 25.0]]
答案 1 :(得分:1)
如果您的实际数据包含类似int
的{{1}},请不要直接使用float
。请改用str
:
float
如果可能有一些空的str x = [['a', '1', ' 2.22', ' 3', '4', ' 5'],
['b', '11', ' 12', ' 13', ' 14', ' 15'],
['c', '21', ' 22', ' 23', ' 24', '25']]
new_list = [list(map(float, s[1:])) for s in x]
print(new_list)
[[1.0, 2.22, 3.0, 4.0, 5.0],
[11.0, 12.0, 13.0, 14.0, 15.0],
[21.0, 22.0, 23.0, 24.0, 25.0]]
:
''