繁体   English   中英

有没有办法将字符串列表转换为 python 中的整数列表?

[英]Is there a way to convert a list of strings to a list of ints in python?

所以我有以下多维列表:

[['50 60 70 60'], 
 ['100 90 87 90'], 
 ['30 65 50 50'], 
 ['58 50 74 43']]

无论如何我可以将字符串转换为整数列表,例如:

[[50, 60, 70, 60], 
 [100, 90, 87, 90], 
 [30, 65, 50, 50], 
 [58, 50, 74, 43]]

您可以使用嵌套列表推导式,在外循环中,迭代子列表,在内循环中,将str.split结果的每个元素转换为int类型:

out = [[int(x) for x in lst[0].split()] for lst in lsts]

Output:

[[50, 60, 70, 60], [100, 90, 87, 90], [30, 65, 50, 50], [58, 50, 74, 43]]

这是一种方法:

in_ = [['50 60 70 60'], 
 ['100 90 87 90'], 
 ['30 65 50 50'], 
 ['58 50 74 43']]

 out = []

 for list_ in in_:
     for nums in list_:
        buff = []
        buf = nums.split(' ')
        for num in buf:
            buff.append(int(num))
    out.append(buff)
    buff = []

print(out)
you can try 
> np.array[[50, 60, 70, 60], 
 [100, 90, 87, 90], 
 [30, 65, 50, 50], 
 [58, 50, 74, 43]]
which will convert str to array..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM