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

后端 未结 11 1113
梦如初夏
梦如初夏 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 15:55

    #declare the string of numbers
    str_nums = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
    
    #zip two lists: the even elements with the odd elements, casting the strings to integers
    zip([int(str_nums.split(',')[i]) for i in range(0,len(str_nums.split(',')),2)],[int(str_nums.split(',')[i]) for i in range(1,len(str_nums.split(',')),2)])
    
    """
    Of course you would want to clean this up with some intermediate variables, but one liners like this is why I love Python :)
    """
    

提交回复
热议问题