“蟒蛇式"将一串逗号分隔的整数解析为整数列表的方法? [英] "pythonic" method to parse a string of comma-separated integers into a list of integers?
本文介绍了“蟒蛇式"将一串逗号分隔的整数解析为整数列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在读取一串整数,例如 "3 ,2 ,6 "
并希望它们在列表 [3,2,6]
中作为整数.这很容易破解,但pythonic"的做法是什么?
I am reading in a string of integers such as "3 ,2 ,6 "
and want them in the list [3,2,6]
as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
推荐答案
mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]
如果您不确定是否只有数字(或想丢弃其他数字):
And if you're not sure you'll only have digits (or want to discard the others):
mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]
这篇关于“蟒蛇式"将一串逗号分隔的整数解析为整数列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文