python中在不同类型数据转换⽅⾯是有标准库的,使⽤⾮常⽅便。但是在开发中,经常在list中字符转成整形的数据⽅便遇到问题。这⾥就记录⼀下常⽤的⼏种⽅法。
⽅法⼀:
最基本的⽅法:通过轮训整个list来实现转换。具体代码如下:
test_list=['1','3','2','6','8']
print("Original list is: " + str(test_list))
out_list=test_list
for i in range(0,len(test_list)):
out_list[i]=int(test_list[i])
print("Out list is: " + str(out_list))
结果:
Original list is: ['1', '3', '2', '6', '8']
Out list is: [1, 3, 2, 6, 8]
⽅法⼆:
使⽤list的复合运算:
test_list=['1','3','2','6','8']
print("Original list is: " + str(test_list))
out_list=[int(i) for i in test_list]
print("Out list is: " + str(out_list))
结果:
Original list is: ['1', '3', '2', '6', '8']
Out list is: [1, 3, 2, 6, 8]
⽅法三:
使⽤map():
test_list=['1','3','2','6','8']
print("Original list is: " + str(test_list))
out_list=list(map(int,test_list))
print("Out list is: " + str(out_list))
结果:
Original list is: ['1', '3', '2', '6', '8']
Out list is: [1, 3, 2, 6, 8]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)