Efficient way to convert strings from split function to ints in Python

后端 未结 4 1377
执笔经年
执笔经年 2020-12-02 20:08

I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 20:39

    You can map the function int on each substring, or use a list comprehension:

    >>> file = '8743-12083-15'
    >>> list(map(int, file.split('-')))
    [8743, 12083, 15]
    >>> [int(d) for d in file.split('-')]
    [8743, 12083, 15]
    

    In the above the call to list is not required, unless working with Python 3.x. (In Python 2.x map returns a list, in Python 3.x it returns a generator.)

    Directly assigning to the three variables is also possible (in this case a generator expression instead of a list comprehension will do):

    >>> xval, yval, zval = (int(d) for d in file.split('-'))
    >>> xval, yval, zval
    (8743, 12083, 15)
    

提交回复
热议问题