我有一个代码用于在Python中列出列表中的每个数字,但我遇到了问题。我的代码没有给我正确的答案。如果我有[2,3,4,5,6,7]
,答案应为[4, 9, 16, 25, 36, 49]
,但我会[49]
。这是我的代码:
numList = [2,3,4,5,6,7]
def square (N):
sq = N * N
return (sq)
def cmput_square(numList):
i = 0
L = []
while i < len (numList):
L = [square(numList[i])]
i = i + 1
return (L)
n = cmput_square (numList)
print ("The squares of your numbers are:", n)
答案 0 :(得分:1)
您的问题是,您每次都要替换L
,而不是追加到L
。以下应该有效:
numList = [2,3,4,5,6,7]
def square (N):
sq = N * N
return (sq)
def cmput_square(numList):
i = 0
L = []
while i < len (numList):
L.append(square(numList[i]))
i = i + 1
return (L)
n = cmput_square (numList)
print ("The squares of your numbers are:", n)
打印:
The squares of your numbers are: [4, 9, 16, 25, 36, 49]
如果您想减少所需的代码行数,可以使用列表迭代将其更改为单个函数:
def cmput_square(numList):
return([i*i for i in numList])
[编辑] 根据您的评论,您无法使用.append
或列表理解,这是另一种方式,同样作为单一功能。我认为它不那么优雅,但它可以满足你的需求:
def cmput_square(numList):
L = [0] * len(numList)
for i in range(len(numList)):
L[i] = numList[i]*numList[i]
return(L)
[编辑#2] 并且不使用for
或range
,您可以这样做:
def cmput_square(numList):
L = [0] * len(numList)
i = 0
while i < len(numList):
L[i] = numList[i]*numList[i]
i = i+1
return(L)
答案 1 :(得分:0)
您创建列表的当前方式会在每次调用时用一个项目列表覆盖L.你可以使用L.append(square(numList[i]))
代替L = [square(numList[i])]
,你可以通过列表理解在一行中创建整个列表:
def cmput_square(numList):
return [square(i) for i in numlist]
答案 2 :(得分:0)
生日快乐 - 只需使用.append()
numList = [2,3,4,5,6,7]
def square (N):
sq = N * N
return (sq)
def cmput_square(numList):
i = 0
L = []
while i < len (numList):
L.append(square(numList[i]))
i += 1
return (L)
n = cmput_square (numList)
print ("The squares of your numbers are:", n)
答案 3 :(得分:-3)
替换
L = [square(numList[i])]
与
L += [square(numList[i])]
如果您想要更短的版本:
numList = [2,3,4,5,6,7]
L = [numList[i]**2 for i in range(len(numList))]
print ("The squares of your numbers are:", L)