Python: string to a list of lists

前端 未结 2 984
梦如初夏
梦如初夏 2021-01-18 08:03

I\'m new to python and confused about converting a string to a list. I\'m unsure how to create a list within a list to accomplish the following:

Ex.



        
相关标签:
2条回答
  • 2021-01-18 08:42
    >>> text = '2,4,6,8|10,12,14,16|18,20,22,24'
    >>> my_data = [x.split(',') for x in text.split('|')]
    >>> my_data
    [['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']]
    >>> print my_data[1][2]
    14
    

    Maybe you also want to convert each digit (still strings) to int, in which case I would do this:

    >>> [[int(y) for y in x.split(',')] for x in text.split('|')]
    [[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]
    
    0 讨论(0)
  • 2021-01-18 08:46
    >>> strs = '2,4,6,8|10,12,14,16|18,20,22,24'
    >>> strs1=strs.split('|')
    >>> [map(int,x.split(',')) for x in strs1] 
    [[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]
    

    Note: for python 3.x use list(map(int,x.split(','))), as map() returns a map object in python 3.x

    0 讨论(0)
提交回复
热议问题