需要帮助编辑列表中的数字平方的Python代码吗?

需要帮助编辑列表中的数字平方的Python代码吗?,python,Python,我有一个用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

我有一个用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)

您的问题是每次都要替换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)
如果希望减少所需的代码行数,可以通过列表迭代将其更改为单个函数:

def cmput_square(numList):
    return([i*i for i in numList])
[编辑]鉴于您无法使用。根据您的评论添加或列表理解,这里是另一种方法,同样作为单个函数。我认为它不那么优雅,但它能满足你的需要:

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) 

当前创建列表的方式在每次调用L时都会用一个项目列表覆盖它。您可以使用L.appendsquarenumList[i]而不是L=[squarenumList[i]],也可以通过列表理解在一行中创建整个列表:

def cmput_square(numList):
    return [square(i) for i in numlist]

生日快乐-只需使用。附加

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)
替换

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)
使用列表上的.append方法。执行L=[squarenumList[i]]只会每次创建一个包含单个元素的新列表并将其分配给L。因此,使用L.appendnumList[i]作为旁注,i=0,而i<…,i=i+1不是执行循环的好方法。对于我来说,rangelennumList:也更简单、更高效。或者,更好的是,你用i做的唯一一件事就是numList[i],所以你可以跳过它,在numList中为num做:.maplambda x:x**2,numList?@aws\u学徒:为什么在这里用map代替理解?这意味着您必须创建一个其他不必要的函数来包装表达式,然后您只需将其转换为一个列表,以便在最后打印出来。
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)