How to convert strings into integers in Python?

后端 未结 15 2143
自闭症患者
自闭症患者 2020-11-22 01:33

I have a tuple of tuples from a MySQL query like this:

T1 = ((\'13\', \'17\', \'18\', \'21\', \'32\'),
      (\'07\', \'11\', \'13\', \'14\', \'28\'),
               


        
15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 02:00

    You can do this with a list comprehension:

    T2 = [[int(column) for column in row] for row in T1]
    

    The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

    The code snippet will fail if any of the rows contain objects that can't be converted by int. You'll need a smarter function if you want to process rows containing non-decimal strings.

    If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

    T2 = [parse_a_row_of_T1(row) for row in T1]
    

提交回复
热议问题