“python”方法来解析一系列逗号分隔的整数到整数列表中?

时间:2021-04-24 00:17:03

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]中。这很容易破解,但是“python化”的方法是什么呢?

3 个解决方案

#1


21  

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()]

#2


14  

map( int, myString.split(',') )

#3


6  

While a custom solution will teach you about Python, for production code using the csv module is the best idea. Comma-separated data can become more complex than initially appears.

虽然定制的解决方案可以教会您有关Python的知识,但是使用csv模块的生产代码是最好的方法。逗号分隔的数据可能比最初出现的更复杂。

#1


21  

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()]

#2


14  

map( int, myString.split(',') )

#3


6  

While a custom solution will teach you about Python, for production code using the csv module is the best idea. Comma-separated data can become more complex than initially appears.

虽然定制的解决方案可以教会您有关Python的知识,但是使用csv模块的生产代码是最好的方法。逗号分隔的数据可能比最初出现的更复杂。