I have [1,2,3] and I wish to get [(1,1,1), (1,4,9), (1, 8, 27)]. What is the easiest way to achieve this?
Thank you in advance! I am using numpy.
CodePudding user response:
I'd probably do this with a list comprehension, an inner loop iterating over your array/list, i. e. [1,2,3]
and an outer loop iterating over the powers , i. e. zero, one and two (EDIT: To achieve the output you specified in your question one would need [0,2,3]
as powers list):
elements = [1,2,3]
powers = [0,1,2]
[[e**i for e in elements] for i in powers]
The output of this is
[[1, 1, 1], [1, 2, 3], [1, 4, 9]]
If you want a numpy array you can convert it with np.array()
and if you want a list of tuples as you have it written in your question convert it with tuple()
, i. e.
import numpy as np
elements = [1,2,3]
powers = [0,1,2]
# numpy array
np.array([[e**i for e in elements] for i in powers])
# list of tuples
[tuple([e**i for e in elements]) for i in powers]
CodePudding user response:
I'd do it this way, check it out:
def get_cuadrado_cubo(lista):
resp = []
for i in range (4):
if i == 1:
continue
resp.append((lista [0] ** i, lista [1] ** i, lista [2] ** i) )
return resp