converting to an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Patrick C
    New Member
    • Apr 2007
    • 54

    converting to an integer

    hey everyone, i'm having a mental block can anyone help me out

    if i have a list like this
    num = ['1;3;2;3;2;1;4' , '\n', '30;2;13;2;1;4; 2', '2;3;2;1;4;2;4' , '3;2;1;4;2;4;1' , '2;1;4;2;4;1;4' , '1;4;2;4;1;4;2']

    how might i get python to recognize each elemant as an integer so that i can sum each list

    that is have it print
    16
    \n
    54
    18

    etc

    thanks
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    [code=Python]>>> num = ['1;3;2;3;2;1;4' , '\n', '30;2;13;2;1;4; 2', '2;3;2;1;4;2;4' , '3;2;1;4;2;4;1' , '2;1;4;2;4;1;4' , '1;4;2;4;1;4;2']
    >>> s = '\n'.join([str(result) for result in [sum([int(i) for i in item.split(';')]) for item in num if item != '\n']])
    >>> s
    '16\n54\n18\n17 \n18\n18'
    >>> print s
    16
    54
    18
    17
    18
    18
    >>> [/code]

    Comment

    • Patrick C
      New Member
      • Apr 2007
      • 54

      #3
      that works well, but i'm trying to keep a blank line if the '\n' was there to begin with, how can i tweak that so the solution would have been

      '16\n\n54\n18\n 17\n18\n18'

      thanks

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        [code=Python]results = []
        for item in num:
        if item == '\n':
        results.append( '')
        else:
        results.append( str(sum([int(i) for i in item.split(';')])))
        print '\n'.join(resul ts)[/code]

        Code:
        >>> 16
        
        54
        18
        17
        18
        18
        >>> print repr('\n'.join(results))
        '16\n\n54\n18\n17\n18\n18'
        >>>
        I got carried away with the list comprehension in my previous post. s could be:[code=Python]s = '\n'.join([str(sum([int(i) for i in item.split(';')])) for item in num if item != '\n'])[/code]

        Comment

        • Patrick C
          New Member
          • Apr 2007
          • 54

          #5
          hey thanks for breaking it up onto many lines, i'm so fresh at this that when it's all squeezed into one line my mind breaks

          Comment

          Working...