You don’t need to create the list with the letters and then turn them into numbers. You can do this whole transformation at once:
nome = "joao da silva pinto".upper()
lista = []
a = ord("A")
for s in nome.split():
lista.append([ord(c) - a + 1 for c in s])
print(lista) # [[10, 15, 1, 15], [4, 1], [19, 9, 12, 22, 1], [16, 9, 14, 20, 15]]
I do the split
of the name, and for each part of the same I create a sub-list corresponding to the values of that part.
Then add this sub-list of values in the results list.
If you want, you can change the loop above by a comprehensilist on, much more succinct and pythonic:
lista = [
[ ord(c) - a + 1 for c in s ]
for s in nome.split()
]
Note: the expression ord(c) - a + 1 for c in list(s)
is also a comprehensilist on, is much more succinct than making another for
within the for
more external. But obviously you can do so too:
lista = []
for s in nome.split():
sublista = []
for c in s:
sublista.append(ord(c) - a + 1)
lista.append(sublista)
You said you wanted to calculate the sum of each sub-list. In this case, instead of creating the sub-lists, just use sum
to add up the values:
lista = [
sum(ord(c) - a + 1 for c in s)
for s in nome.split()
]
print(lista) # [41, 5, 63, 74]
Or, if you don’t want to use the comprehensilist on to build the list:
lista = []
for s in nome.split():
lista.append(sum(ord(c) - a + 1 for c in s))
And of course you could also do the sums manually:
lista = []
for s in nome.split():
soma = 0
for c in s:
soma += ord(c) - a + 1
lista.append(soma)
If want to transform the list of letters in their respective numbers, there would be so:
# pode usar seu código mesmo para gerar esta lista de letras
letras = [['J', 'O', 'A', 'O'], ['D', 'A'], ['S', 'I', 'L', 'V', 'A'], ['P', 'I', 'N', 'T', 'O']]
numeros = []
for sublista in letras:
n = []
for c in sublista:
n.append(ord(c) - a + 1)
numeros.append(n)
Or, using comprehensilist on:
numeros = [ list(map(lambda c: ord(c) - a + 1, sublista)) for sublista in letras ]
Here I used map
to turn each sub-list item into its number.
And if you want to calculate the sum:
numeros = []
for sublista in letras:
soma = 0
for c in sublista:
soma += ord(c) - a + 1
numeros.append(soma)
print(numeros)
# ou, com list comprehension
numeros = [ sum(map(lambda c: ord(c) - a + 1, sublista)) for sublista in letras ]
Interesting question.
– ClMend