How to create simple list from composite list?

Asked

Viewed 200 times

1

What is wrong here? I would like the output to be [123, 456, 789]:

a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = []

for num in a:
    x = ''
    for num2 in num:
        x.join(num2)
    b.append(x)

print(b)

1 answer

4


Each element of a is a tuple with 3 numbers. To join them together, you can turn them into string, join everything with join and convert the result back to number:

a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = [int(''.join(str(n) for n in numeros)) for numeros in a]
print(b)

But if you want, you can also use a little math to transform (1, 2, 3) in 123:

def juntar_numeros(numeros):
    return sum(n * 10 ** (len(numeros) - 1 - i) for i, n in enumerate(numeros))

a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]    
b = [juntar_numeros(numeros) for numeros in a]
print(b)

The idea is to use the index of each element to know the power of 10 corresponding. For this use enumerate, which makes it possible to obtain the element and its index at the same time.

The result of both is the list [123, 456, 789].


In the above codes I used the syntax of comprehensilist on, much more succinct and pythonic.

For those who are not used to it, it may seem a little difficult to understand. Another way of doing it would be:

# transformar em string, join e converter para número depois
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = []

for numeros in a:
    # map converte os números para strings, para poderem serem unidos no join
    b.append(int(''.join(map(str, numeros))))

print(b)

# solução matemática
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

def juntar_numeros(numeros):
    result = 0
    for i, n in enumerate(numeros):
        result += n * 10 ** (len(numeros) - 1 - i)
    return result

b = []
for numeros in a:
    b.append(juntar_numeros(numeros))

print(b)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.