简体   繁体   English

将字符串列表列表转换为 Python 中的 integer

[英]Converting list of lists of strings into integer in Python

I want to convert the string elements to integers within the each following list:我想将字符串元素转换为以下每个列表中的整数:

old = [['29,1,22,14,32,11,11,3'],
 ['2,3,1,2,1,4,1,1,3,1'],
 ['5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7'],
 ['2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2'],
 ['29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5']]

I have tried the following codes:我尝试了以下代码:

[[int(num) for num in sub] for sub in old]
[list(map(int, sublist)) for sublist in old]

These are not working in my case.这些在我的情况下不起作用。 I need the following outputs:我需要以下输出:

new = [[29,1,22,14,32,11,11,3],
 [2,3,1,2,1,4,1,1,3,1],
 [5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7],
 [2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2],
 [29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5]]

You have the right idea with both of the approaches you just didn't account for the seperator, ie, the commas.你对这两种方法都有正确的想法,你只是没有考虑分隔符,即逗号。 As the numbers are separated by commas you need to split() them before converting to int由于数字用逗号分隔,因此您需要在转换为int之前将它们split()

[[int(num) for num in sub[0].split(",")] for sub in old]

[list(map(int, sublist[0].split(","))) for sublist in old]

Try:尝试:

old = [['29,1,22,14,32,11,11,3'],
 ['2,3,1,2,1,4,1,1,3,1'],
 ['5,2,1,1,3,1,2,4,1,1,2,2,2,1,19,2,1,7'],
 ['2,2,1,5,6,1,2,3,9,2,1,1,2,6,1,1,2,3,1,1,2'],
 ['29,44,5,8,17,20,26,47,80,29,47,17,23,26,46,69,8,2,5,38,8,5,5']]

new = [[int(x) for x in sublst[0].split(',')] for sublst in old]
# new = [list(map(int, sublst[0].split(','))) for sublst in old] # an alternative

print(new)
# [[29, 1, 22, 14, 32, 11, 11, 3], [2, 3, 1, 2, 1, 4, 1, 1, 3, 1], [5, 2, 1, 1, 3, 1, 2, 4, 1, 1, 2, 2, 2, 1, 19, 2, 1, 7], [2, 2, 1, 5, 6, 1, 2, 3, 9, 2, 1, 1, 2, 6, 1, 1, 2, 3, 1, 1, 2], [29, 44, 5, 8, 17, 20, 26, 47, 80, 29, 47, 17, 23, 26, 46, 69, 8, 2, 5, 38, 8, 5, 5]]

You need to use split to parse each long string into small strings, and then apply int to convert a string into an int.你需要使用split将每个长字符串解析成小字符串,然后应用int将字符串转换为 int。

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

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