Python Squares函数

2024-05-19 15:06:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它将返回一个正方形数字列表,但如果函数接受参数(“apple”)或(范围(10))或列表,则将返回一个空列表。我已经完成了第一部分,但是如果参数n不是整数,我就不知道如何返回空集-我一直收到一个错误:unorderable types:str()>;I n t() 我知道字符串不能与整数进行比较,但我需要它返回空列表。

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

Tags: 函数apple列表参数returndef错误数字
3条回答

可以使用python中的type函数检查变量的数据类型。为此,您可以使用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

不能像以前那样将字符串与整数进行比较。如果要检查n是否为整数,可以使用isinstance()

def squares(n):
    squareList = []
    if isinstance(n, (int, float)) and n > 0: # If n is an integer or a float
        squareList = list(map(square,range(1,n+1)))     
    return squareList

现在,如果字符串或列表作为参数给定,函数将立即返回空列表[]。否则,它将继续正常运行。


一些例子:

print(squares('apple'))
print(squares(5))
print(squares(range(10)))

将返回:

[]
[1, 4, 9, 16, 25]
[]

您可以使用or将导致返回空列表的所有条件链接到一个条件中。例如,如果它是一个列表,或等于'apple',或等于range(10)n < 0,则返回空列表。否则返回映射结果。

def square(n):
    return n**2

def squares(n):
   if isinstance(n,list) or n == 'apple' or n == range(10) or n < 0:
      return []
   else:
      return list(map(square,range(1,n+1)))

isinstance检查n是否是list的实例。

一些测试用例:

print squares([1,2])
print squares('apple')
print squares(range(10))
print squares(0)
print squares(5)

获取

[]
[]
[]
[]
[1, 4, 9, 16, 25]
>>> 

相关问题 更多 >