Reputation: 3227
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
Reputation: 6456
simply put:
flattening the list
[e for e in (itertools.chain(*x))]
removing the negative sign
e.replace('-','')
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
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
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
Reputation: 11744
>>> int(''.join(reduce(lambda a, b: a + b, x)))
4850775602376340
Upvotes: 6
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
Reputation: 188014
>>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]
>>> int(''.join([''.join(i) for i in x ] ))
4850775602376340
Upvotes: 1