python: convert “5,4,2,4,1,0” into [[5, 4], [2, 4], [1, 0]]

后端 未结 11 1122
梦如初夏
梦如初夏 2020-11-28 15:33

Is there a \"straightforward\" way to convert a str containing numbers into a list of [x,y] ints?

# from: \'5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5\'
# to: [[5, 4         


        
11条回答
  •  孤街浪徒
    2020-11-28 16:05

    One option:

    >>> num_str = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5'
    >>> l = num_str.split(',')
    >>> zip(l[::2], l[1::2])
    [('5', '4'), ('2', '4'), ('1', '0'), ('3', '0'), ('5', '1'), ('3', '3'), ('4', '3'), ('3', '5')]
    

    Reference: str.split(), zip(), General information about sequence types and slicing

    If you actually want integers, you could convert the list to integers first using map:

    >>> l = map(int, num_str.split(','))
    

    Explanation:

    split creates a list of the single elements. The trick is the slicing: the syntax is list[start:end:step]. l[::2] will return every second element starting from the first one (so the first, third,...), whereas the second slice l[1::2] returns every second element from the second one (so the second, forth, ...).

    Update: If you really want lists, you could use map again on the result list:

    >>> xy_list = map(list, xy_list)
    

    Note that @Johnsyweb's answer is probably faster as it seems to not do any unnecessary iterations. But the actual difference depends of course on the size of the list.

提交回复
热议问题