我正在编写一个函数,该函数将返回一个平方数列表,但是如果该函数采用参数('apple')或(range(10))或一个列表,则将返回一个空列表。我已经完成了第一部分,但无法弄清楚如果参数n不是整数,如何返回空集-我一直收到错误:无序类型:str()> int()我知道字符串可以可以与一个整数进行比较,但是我需要它来返回空列表。
def square(n):
return n**2
def Squares(n):
if n>0:
mapResult=map(square,range(1,n+1))
squareList=(list(mapResult))
else:
squareList=[]
return squareList
Run Code Online (Sandbox Code Playgroud)
您可以type在python中使用该函数来检查变量的数据类型。为此,您将用于type(n) is int检查是否n是所需的数据类型。另外,map已经返回一个列表,因此不需要强制转换。因此...
def Squares(n):
squareList = []
if type(n) is int and n > 0:
squareList = map(square, range(1, n+1))
return squareList
Run Code Online (Sandbox Code Playgroud)