Fork me on GitHub

  python中在不同类型数据转换方面是有标准库的,使用非常方便。但是在开发中,经常在list中字符转成整形的数据方便遇到问题。这里就记录一下常用的几种方法。

 

方法一:最基本的方法:通过轮训整个list来实现转换,具体代码如下:

# Python3 code to demonstrate
# converting list of strings to int
# using naive method

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))

 

方法二:使用list的复合运算:

 

# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension

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))

 

方法三: 使用map():

 

# Python3 code to demonstrate
# converting list of strings to int
# using 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]

 

 

 

     

 

posted on 2020-11-02 11:42  虚生  阅读(17836)  评论(0编辑  收藏  举报