将一串逗号分隔的整数解析为整数列表的“pythonic”方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3477502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"pythonic" method to parse a string of comma-separated integers into a list of integers?
提问by pythonsupper
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?
我正在读取一串整数,例如"3 ,2 ,6 "并希望它们[3,2,6]作为整数出现在列表中。这很容易破解,但是“pythonic”的做法是什么?
回答by Wayne Werner
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()]
回答by Eli Bendersky
While a custom solution will teach you about Python, for production code using the csvmodule is the best idea. Comma-separated data can become more complex than initially appears.
虽然自定义解决方案会教您有关 Python 的知识,但对于使用该csv模块的生产代码来说,这是最好的主意。逗号分隔的数据可能会变得比最初出现的更复杂。
回答by wheaties
map( int, myString.split(',') )

