Example: input a=[1,2,3] b=[4,5,6]
output ->[4,10,18]
First, create something that works even if it is dirty. After that, refactor if you can afford it. First write the contents, and if it moves, make it a function
a=[1, 2, 3]
b=[4, 5, 6]
[a[0] * b[0], a[1] * b[1], a[2] * b[2]]
#output
[4, 10, 18]
It worked for the time being.
def calc(a, b):
return [a[0] * b[0], a[1] * b[1], a[2] * b[2]]
However, with this, if the number of elements in the list increases or decreases by one, it cannot be dealt with. Code that is not versatile. So refactor it to make it more versatile.
calc_results = []
for i in range(len(a)):
calc_results.append(a[i] * b[i])
Create a list, multiply it by the length of the list, and store it in the list. With this, you can handle any number of elements in the list.
def calc(a,b):
calc_results = []
for i in range(len(a)):
calc_results.append(a[i] * b[i])
return calc_results
However, this makes the code cluttered, so the next step is to improve readability.
calc_results = []
for (x,y) in zip (a,b):
calc_results.append(x * y)
calc_results
If you want to get and use elements such as lists and tuples at the same time, specify them in the argument of the zip () function.
def calc(a,b):
calc_results = []
for (x,y) in zip (a,b):
calc_results.append(x * y)
return calc_results
If you do it individually, I think that even a dirty program can be managed with a spirit of movement for the time being, but if you develop it as a team, I think that it is better to have code that is easy to maintain and has high readability and versatility, so it is best to make something that works first. I think it's important, but maybe you should refactor your code after that.
Recommended Posts