[英]How to make sure if parameter is a list of numbers? (python)
I've been working on Bézier curve and I got everything working fine, but I want to make sure user will enter proper input. 我一直在研究Bézier曲线 ,我把一切都搞好了,但我想确保用户输入正确的输入。
I need statement checking if entered value is a list containing exactly two numbers, let it be integers or floats. 我需要声明检查输入的值是否是包含两个数字的列表,让它成为整数或浮点数。 More info is always welcome.
欢迎提供更多信息。
If anyone needs the code, here you go. 如果有人需要代码,那么你去吧。 (There's probably just a formula for it somewhere, and this here is inefficient. ^^)
(在某个地方可能只有一个公式,这里效率很低。^^)
#finding a point on vector based on start point, end and %
def findPoint(t, A, B):
'''
findPoint( 'float member of <0, 1>',
'coordinates of point A written as [x, y]',
'coordinates of point B written as [x, y]')
'''
x=(B[0]-A[0])*t+A[0]
y=(B[1]-A[1])*t+A[1]
return [x, y]
#find coordinates of a point on the bezier curve
def bezierCurve(t, *points):
pointList=[]
for X in points:
pointList.append(X)
while len(pointList) !=1:
tempList=[]
for i in xrange(0, len(pointList)-1):
tempList.append(findPoint(t, pointList[i], pointList[i+1]))
pointList=tempList
return pointList.pop()
You could check that all of the elements are int
(or float
) by using all
你可以检查所有的元素都是
int
(或float
)通过使用all
>>> l = [1,2,3]
>>> a = ['a','b','c']
>>> all(isinstance(i, int) for i in l)
True
>>> all(isinstance(i, int) for i in a)
False
Also you could check that len(list) == 2
你也可以检查
len(list) == 2
So as a function it could be something like 所以作为一个功能,它可能是这样的
def twoNumValues(myList):
return len(myList) == 2 and all(isinstance(i, int) or isinstance(i, float) for i in myList)
Or 要么
def twoNumValues(myList):
return len(myList) == 2 and all(type(i) in [float, int] for i in myList)
This is a one line function to test the parameters you describe: 这是一个单行函数来测试您描述的参数:
def check(l):
return len(l) == 2 and all(type(i) in (int, float) for i in l)
First check that the length is exactly 2, then check that both (all) of them are either int or float. 首先检查长度是否正好为2,然后检查它们(全部)是int还是float。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.