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

后端 未结 11 1108
梦如初夏
梦如初夏 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:44

    You can shorten the first part (converting "1,2,3" to [1, 2, 3]) by using the split function:

    num_list = num_str.split(",")
    

    There might be an easier way to get pairs, but I'd do something like this:

    xy_pairs = []
    for i in range(0, len(num_list), 2):
        x = num_list[i]
        y = num_list[i + 1]
        xy_pairs.append([x, y])
    

    Also, since these are all lists of a defined length (2), you should probably use a tuple:

    xy_pairs.append((x, y))
    

提交回复
热议问题