Python-将带有数字的字符串转换为整数列表 [英] Python - Convert string with numbers into a list of integers
本文介绍了Python-将带有数字的字符串转换为整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在SO上阅读了有关此问题的几个问题,但是这些问题都没有为我解决-我想我做错了.
I've read several questions about this on SO, however, none of them worked out for me - I guess I'm doing something wrong.
我有一个字符串,数字用逗号和空格隔开,如下所示:
I have a string with numbers separated with commas and spaces which looks like this:
my_string = '32, 76, 82, 19, 25'
现在我想拥有的是上面字符串中数字的整数列表,因此我可以像这样从中提取单个整数:
Now what I would like to have is a list of integers of the numbers in the string above, so I can extract single integers from it like this:
print my_list[2]
>>>82
或
print my_list[4]
>>>25
提前谢谢!
推荐答案
将问题分为两部分.
1将文本拆分为包含所需数据的列表,然后过滤其他文本.
1 Split the text into a list with the data you need and filter the other.
num_list = my_string.split(',')
2将数据转换为所需的类型
2 Convert the data into what type you want it
integers = [int(x) for x in num_list]
然后您可以清理它
integs = [int(x) for x in my_string.split(',')]
这篇关于Python-将带有数字的字符串转换为整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文