How to convert a string with comma-delimited items to a list in Python?

后端 未结 14 641
予麋鹿
予麋鹿 2020-11-28 03:09

How do you convert a string into a list?

Say the string is like text = \"a,b,c\". After the conversion, text == [\'a\', \'b\', \'c\'] and h

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 04:06

    To convert a string having the form a="[[1, 3], [2, -6]]" I wrote yet not optimized code:

    matrixAr = []
    mystring = "[[1, 3], [2, -4], [19, -15]]"
    b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
    for line in b.split('], ['):
        row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
        matrixAr.append(row)
    print matrixAr
    

提交回复
热议问题