将列表字符串类型元素转化为整型

一维列表

方法一:

a = ['1', '2', '3']
a = list(map(int, a))

方法二:

a = ['1', '2', '3']
a_new = []
for i in a:
    a_new.append(int(i))

方法三:

a = ['1', '2', '3']
a = [int(i) for i in a]

二维列表

二维列表修改元素类型目前没发现更好的方法,只能全部遍历一遍,效率偏低。以后发现更好的方法再添加。

方法一:元素级操作

# 将food_data_list(二位列表)的数据str->float
food_intList = []
for i in range(len(food_data_list)):
    point1 = [float(food_data_list[i][0]), float(food_data_list[i][1]), float(food_data_list[i][2])]
    food_intList.append(point1)

转化前后结果:

在这里插入图片描述
方法二:对内层一维列表进行类型转换

b = [['1', '2'], ['3', '4']]
b_new = []
for i in b:
    i_new = list(map(int, i))
    b_new.append(i_new)

print(b_new)

在这里插入图片描述

你可能感兴趣的:(Python,python)