1
I have the following list:
X = [1,2,3,4,5]
I want you to stay like this:
X = [[1],[2],[3],[4],[5]]
1
I have the following list:
X = [1,2,3,4,5]
I want you to stay like this:
X = [[1],[2],[3],[4],[5]]
1
Simply iterate the list and encapsulate each of the elements in an array.
example:
lista = [1,2,3,4, 40]
novalista = []
for x in lista:
novalista.append([x])
print(novalista)
novalista
will contain the desired result.
If the value of lista
is different, like lista = [1,2,3,40]
, This doesn’t work. I don’t understand why novalista.append([lista[x-1]])
and not just novalista.append([x])
. Could you explain to me?
Really the lista[x-1]
did not make any sense and so I left my negative vote. If you correct the answer, I will be able to review my vote.
small collapse, but already this corrected!
1
With list comprehension just do:
nova_lista = [[i] for i in X]
Using numpy
, we can change the shape of array
:
import numpy
X = [1,2,3,4,5]
nova_lista = numpy.array(X).reshape(len(X),1)
0
Well...here I have a list where the values within it are changeable, IE, as the system evolves, it automatically changes. Ex: Months of the year, where I can have a list that starts in December, and is in May(present day). This list would then be like this:
meses = [12,1,2,3,4,5]
With the list being so, I resolved quietly with the suggestion of correction of colleague Alexciuffa.
X = []
for x in months_list_number:
X.append([x])
So the result obtained in the print was:
[[12],[1],[2],[3],[4],[5]]
So why not use (and accept) his answer? I see no reason not to use list comprehension in this case.
Browser other questions tagged python list
You are not signed in. Login or sign up in order to post.
In order for you to get better answers you better put here what you have already done, how is your code, where is giving error... Not just what you want to do.
– Leticia Rosa