簡體   English   中英

我正在嘗試將數字放入列表並平方並全部打印出來

[英]I'm trying to put numbers into a list and square and print them all

因此,我正在嘗試將數字放入列表並平方並打印所有內容。

這就是我所擁有的:

import math
ListNum = [2,4,6,8]
for item in ListNum:
    list(map(float, ListNum)
print(math.sqrt(ListNum))

但是然后我有這個錯誤:

文件“ Main.py”,第5行print(math.sqrt(ListNum))^ SyntaxError:語法無效

第5行打印出來的東西。 有誰能幫上忙嗎?

這有效:

import math
ListNum = [2,4,6,8]
for item in ListNum:
    print (math.sqrt(item))
    print (item*item)

區別在於,這里要打印列表中的每個項目,而不是列表本身。

第一行print (math.sqrt(item))打印平方根,第二行print (math.sqrt(item)) print (item*item)打印平方。

為什么不僅僅創建一個包含結果的列表(使用列表理解),然后打印(以任何格式)呢?

from math import sqrt

ListNum = [2,4,6,8]

ret = [sqrt(x) for x in ListNum]
print(ret)

要回答原始問題-SyntaxError是由於缺少第4行上的右圓括號list(map(float, ListNum)應該是list(map(float, ListNum)) 。有時錯誤在上一行(在這種情況下,第4行),而不是回溯中指示的內容(在本例中為第5行)。盡管如此,代碼仍無法實現您的期望,請參見其他答案。

import math
ListNum = [2,4,6,8]
for item in ListNum:
    list(map(float, ListNum)  <--- you miss a parenthese
print(math.sqrt(ListNum))

math.sqrt正在計算平方根:

>> help(math.sqrt)
sqrt(...)
    sqrt(x)

    Return the square root of x.

對於平方:

import math
ListNum = [2,4,6,8]
result = list(map(math.pow, ListNum, [2]*len(ListNum)))

對於平方根:

import math
ListNum = [2,4,6,8]
result = list(map(math.sqrt, ListNum))

在python3文檔中,您可以在底部找到鏈接,math.sqrt()被描述為“返回x的平方根”。 由於ListNum實際上是一個列表,因此math.sqrt()將難以識別數字以外的任何類型。

並且'SyntaxError'來自第4行末尾缺少的')'。

以下代碼可以工作。

import math
ListNum = [2,4,6,8]
ListNum = list(map(math.sqrt,ListNum))
print (ListNum)

https://docs.python.org/3/library/math.html

您不能取列表的平方根,而ListNum是一個列表。

如果要取所有數字的平方根 (不是平方),可以將math.sqrt映射到該列表:

import math
ListNum = [2,4,6,8]
roots = list(map(math.sqrt, ListNum))
print(roots)

注意沒有循環。 迭代被抽象到map

如果要對數字求平方 ,則需要平方函數:

def square(x) : return x * x
print(list(map(square, ListNum)))

要么

print(list(map(lambda x: x* x, ListNum)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM