harpalss
harpalss

Reputation: 3227

Python: List to ints to a single number?

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.

Upvotes: 1

Views: 2054

Answers (7)

João Portela
João Portela

Reputation: 6456

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))]))

Upvotes: 1

Johannes Charra
Johannes Charra

Reputation: 29913

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'

Upvotes: 1

ChristopheD
ChristopheD

Reputation: 116137

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)))

Upvotes: 6

SilentGhost
SilentGhost

Reputation: 319551

>>> int(''.join(j for i in x for j in i))
4850775602376340

Upvotes: 4

Alex Brasetvik
Alex Brasetvik

Reputation: 11744

>>> int(''.join(reduce(lambda a, b: a + b, x)))
4850775602376340

Upvotes: 6

Jochen Ritzel
Jochen Ritzel

Reputation: 107598

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))

Upvotes: 2

miku
miku

Reputation: 188014

>>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]
>>> int(''.join([''.join(i) for i in x ] ))
4850775602376340

Upvotes: 1

Related Questions