How to convert strings into integers in Python?

后端 未结 15 1877
自闭症患者
自闭症患者 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 01:44

    If it's only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There's a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

    Eval is not what you want to do, in case there's something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).

    0 讨论(0)
  • 2020-11-22 01:47

    I want to share an available option that doesn't seem to be mentioned here yet:

    rumpy.random.permutation(x)
    

    Will generate a random permutation of array x. Not exactly what you asked for, but it is a potential solution to similar questions.

    0 讨论(0)
  • 2020-11-22 01:48

    Python has built in function int(string) and optional parameter base.

    if your string contains an Integer value, it will convert that to the corresponding Integer value. However if you have decimnal number as string you'll need float() to convert it.

    Usage:

    a = '22'
    b = int(a)
    

    and

    if a = '22.22'
    b = int(a) '''will give error, invalid literal for int().'''
    b = float(a) '''will convert the string.'''
    
    0 讨论(0)
  • 2020-11-22 01:50

    You can do something like this:

    T1 = (('13', '17', '18', '21', '32'),  
         ('07', '11', '13', '14', '28'),  
         ('01', '05', '06', '08', '15', '16'))  
    new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
    print(new_list)  
    
    0 讨论(0)
  • 2020-11-22 01:51

    int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

    print (int("1") + 1)
    

    The above prints 2.

    If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 2:

    T2 = [map(int, x) for x in T1]
    

    In Python 3:

    T2 = [list(map(int, x)) for x in T1]
    
    0 讨论(0)
  • 2020-11-22 01:55
    T3=[]
    
    for i in range(0,len(T1)):
        T3.append([])
        for j in range(0,len(T1[i])):
            b=int(T1[i][j])
            T3[i].append(b)
    
    print T3
    
    0 讨论(0)
提交回复
热议问题