[英]How to make sure if parameter is a list of numbers? (python)
我一直在研究Bézier曲線 ,我把一切都搞好了,但我想確保用戶輸入正確的輸入。
我需要聲明檢查輸入的值是否是包含兩個數字的列表,讓它成為整數或浮點數。 歡迎提供更多信息。
如果有人需要代碼,那么你去吧。 (在某個地方可能只有一個公式,這里效率很低。^^)
#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()
你可以檢查所有的元素都是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
你也可以檢查len(list) == 2
所以作為一個功能,它可能是這樣的
def twoNumValues(myList):
return len(myList) == 2 and all(isinstance(i, int) or isinstance(i, float) for i in myList)
要么
def twoNumValues(myList):
return len(myList) == 2 and all(type(i) in [float, int] for i in myList)
這是一個單行函數來測試您描述的參數:
def check(l):
return len(l) == 2 and all(type(i) in (int, float) for i in l)
首先檢查長度是否正好為2,然后檢查它們(全部)是int還是float。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.