I have a list of list(tuple of tuple?) of number
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I want to transform in:
(123,456,789)
I did with this code, can you suggest to me a better way to do it?
listacomb = []
for list in permdue:
for number in list:
numerix = "".join(str(number))
listacomb.append(numerix)
numerix=""
return listacomb
CodePudding user response:
You can do a list comprehension:
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = tuple([int("".join(map(str, inner_list))) for inner_list in data])
print(output)
Output:
(123, 456, 789)
References:
CodePudding user response:
Here is a math approach to doing this. We can iterate each sublist backwards and build out the desired number.
permdue = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
listacomb = []
for list in permdue:
list = reversed(list)
m = 1
numerix = 0
for number in list:
numerix = number * m
m = m * 10
listacomb.append(numerix)
print(listacomb) # [123, 456, 789]
This approach avoids the performance penalizing string solution. It works, for example, by taking [1, 2, 3]
and computing 3 20 100
, to obtain 123.
CodePudding user response:
It can be done without reversal like this:
permdue = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
listacomb = []
for p in permdue:
n = 0
for p_ in p:
n = n * 10 p_
listacomb.append(n)
print(listacomb)
Output:
[123, 456, 789]