tags:

views:

212

answers:

8

Say i have a several list if ints:

x =  [['48', '5', '0'], ['77', '56', '0'],
['23', '76', '34', '0']]

I want this list to be converted to a single number, but the the single number type is still an integer i.e.:

4850775602376340

i have been using this code to carry out the process:

num = int(''.join(map(str,x)))

but i keep getting a value error.

Also if my list contained negative integers how would i convert them to there absolute value? Then convert them to a single number?

x2 = [['48', '-5', '0'], ['77', '56', '0'], ['23', '76', '-34', '0']]

x2 = 4850775602376340

Thanks in advance.

+1  A: 
>>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]
>>> int(''.join([''.join(i) for i in x ] ))
4850775602376340
The MYYN
And to turn it into an actual int, wrap the `int()` call around it.
Amber
+1  A: 

Its a list of lists, so

num = int(''.join(''.join(l) for l in lists))

or

def flatten( nested ):
    for inner in nested:
        for x in inner:
            yield x

num = ''.join(flatten(lists))
THC4k
+5  A: 
>>> int(''.join(reduce(lambda a, b: a + b, x)))
4850775602376340
Alex Brasetvik
Thanks a bunch!
harpalss
just another quick question how woould i raise and error if the single number didnt contain and integer?
harpalss
@harpalss: you can loop through the items and check type(i)==int if you want to make sure
mizipzor
The int()-call will raise a ValueError in that case.
Alex Brasetvik
+3  A: 
>>> int(''.join(j for i in x for j in i))
4850775602376340
SilentGhost
+5  A: 

I'd use itertools.chain.from_iterable for this (new in python 2.6)

Example code:

import itertools
x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]
print int(''.join(itertools.chain.from_iterable(x)))
ChristopheD
A: 

a = ''

for i in range(len(x)): for j in range(len(x[i])): a = a + x[i][j]

a = int(a)

+1  A: 

Enough good answers already ... just wanted to add the treatment of unlimited nesting:

def flatten(obj):
    if not isinstance(obj, list):
        return obj
    else:
        return ''.join([flatten(x) for x in obj])

>>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]
>>> flatten(x)
'4850775602376340'

>>> x = [['48', '5', '0'], ['77', '56', '0'], [['23','123'], '76', '34', '0']]
>>> flatten(x)
'4850775602312376340'
jellybean
recursion is always nice ;)
João Portela
+1  A: 

simply put:

  1. flattening the list

    [e for e in (itertools.chain(*x))]
    
  2. removing the negative sign

    e.replace('-','')
    
  3. joining the numbers in a list into a string and turning it into a number

    int(''.join(x))
    

putting it all together

x2 = int(''.join([e.replace('-','') for e in (itertools.chain(*x))]))
João Portela