python中把list列表所有或者部分的数变成整数,或者浮点数,字符串等等

第一种 简单形式列表中是数字型


list_x = [1624865249825.0, 316.0, 351.0, 32.0, 107.0, 4.0, 1.7187, 2970.0, -1.0]
list_y = [5249825, 4.0, 925, 0.3903, 1.7187, 0.2296, 2970.0, -1.0]

list_x = list(map(int, list_x[1:5]))
list_y = list(map(int, list_y[:]))
list_f = list(map(float, list_y[:]))
list_s = list(map(str, list_y[:]))

print(list_x, "\n", list_y, "\n", list_f, "\n", list_s)
输出:
	[316, 351, 32, 107] 
	[5249825, 4, 925, 0, 1, 0, 2970, -1] 
	[5249825.0, 4.0, 925.0, 0.0, 1.0, 0.0, 2970.0, -1.0] 
	['5249825', '4', '925', '0', '1', '0', '2970', '-1']

第二种 列表中是字符型

import re

if __name__ == '__main__':
    list_diff = ['256,131,318,189,9', '254,203,302,263,9', '225,253,325,333,9',
                 '276,296,341,365,9', '265,345,321,392,9', '243,420,330,490,9',
                 '543,644,551,663,19', '563,647,571,663,19', '782,636,797,643,19']
    list_data_int = []
    
    for str_data in list_diff:
        data_list = re.findall(r"\d+", str_data)
        data_list = list(map(int, data_list[:]))
        print(data_list)
        for data in data_list:
            list_data_int.append(data)
    
    print(list_data_int)

输出:
	[256, 131, 318, 189, 9]
	[254, 203, 302, 263, 9]
	[225, 253, 325, 333, 9]
	[276, 296, 341, 365, 9]
	[265, 345, 321, 392, 9]
	[243, 420, 330, 490, 9]
	[543, 644, 551, 663, 19]
	[563, 647, 571, 663, 19]
	[782, 636, 797, 643, 19]

	[256, 131, 318, 189, 9, 
	254, 203, 302, 263, 9, 
	225, 253, 325, 333, 9, 
	276, 296, 341, 365, 9, 
	265, 345, 321, 392, 9, 
	243, 420, 330, 490, 9, 
	543, 644, 551, 663, 19, 
	563, 647, 571, 663, 19, 
	782, 636, 797, 643, 19]

    原文作者:锦鲤AI幸运
    原文地址: https://blog.csdn.net/qq_37700257/article/details/119652975
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞