问题
I have a list like [2,3,4,5]
and i want square of these number using python function
Have tried below Python code
def square(list=[]):
for i in list:
new_value=[]
new_value.append(i**2)
return new_value
I get the square of only first entry in a list.
square(2,3,4)
回答1:
List comprehension makes this function a single liner and much clearer.
def square(x):
return [y**2 for y in x]
回答2:
Your method square
is initialising new_value
for every element in the list, and also your return is incorrectly placed inside the loop.
def square(list=[]):
new_value=[]
for i in list:
new_value.append(i**2)
return new_value
来源:https://stackoverflow.com/questions/58898374/python-function-for-square-in-a-provided-list