Python平方函数
我正在编写一个函数,该函数将返回一个平方数列表,但如果该函数接受参数('apple')或(范围(10))或列表,则将返回一个空列表。我已经完成了第一部分,但不知道如果参数n不是整数,如何返回空集-我一直收到一个错误:无序类型:str()>int() 我知道字符串不能与整数比较,但我需要它来返回空列表Python平方函数,python,python-3.x,Python,Python 3.x,我正在编写一个函数,该函数将返回一个平方数列表,但如果该函数接受参数('apple')或(范围(10))或列表,则将返回一个空列表。我已经完成了第一部分,但不知道如果参数n不是整数,如何返回空集-我一直收到一个错误:无序类型:str()>int() 我知道字符串不能与整数比较,但我需要它来返回空列表 def square(n): return n**2 def Squares(n): if n>0: mapResult=map(square,range
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
您不能像以前那样将字符串与整数进行比较。如果要检查
n
是否为整数,可以使用isinstance()
:
现在,如果一个字符串或列表作为参数给出,函数将立即返回一个空列表[]
。如果没有,它将继续正常运行
一些例子:
print(squares('apple'))
print(squares(5))
print(squares(range(10)))
将返回:
[]
[1, 4, 9, 16, 25]
[]
您可以使用
或将导致返回空列表的所有条件链接到一个条件中。i、 e如果它是一个列表,或等于'apple'
,或等于范围(10)
或n<0
,则返回一个空列表。否则返回mapResult
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)))
得到
可以使用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
你得到了什么错误?我猜你想要一个尝试…除了
块。你不需要使用映射
,也不需要定义辅助函数正方形
。使用列表理解:[nn**2表示n中的nn]
…或者如果您坚持不使用列表理解映射(lambda x:x**2,…)
Python 3范围是否支持相等?从一些实验来看,它们似乎是这样的:>范围(1,10)=范围(1,10)真>>范围(1,10)=范围(1,9)假
。然而,阅读它们似乎不是吗?isinstance
更好。它处理继承。
print squares([1,2])
print squares('apple')
print squares(range(10))
print squares(0)
print squares(5)
[]
[]
[]
[]
[1, 4, 9, 16, 25]
>>>
def Squares(n):
squareList = []
if type(n) is int and n > 0:
squareList = map(square, range(1, n+1))
return squareList