這個問題在這里已經有了答案: 檢查串列的所有元素是否屬于同一型別 11 個答案 3 小時前關閉。
撰寫一個函式 find_negatives,它以數字串列 l 作為引數,并回傳 l 中所有負數的串列。如果 l 中沒有負數,則回傳一個空串列。
def find_negatives(l):
l_tmp = []
for num in l:
if num < 0:
l_tmp.append(num)
return l_tmp
#Examples
find_negatives([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives([0, 1, 2, 3, 4, 5]) # Expected output: []
這是我在下面遇到問題的部分:
撰寫一個函式 find_negatives2,它的作業原理與 find_negatives 相同,并添加以下兩個內容:
如果 l 不是串列,則回傳字串“無效的引數型別!” 如果 l 中的任何元素既不是整數也不是浮點數,則回傳字串“Invalid parameter value!”
到目前為止我所擁有的
def find_negatives2(l):
l_tmp1 = []
if type(l) != list:
return "Invalid parameter type!"
else:
for num in l:
Examples:
find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives2([0, 1, 2, 3, 4, 5]) # Expected output: []
find_negatives2(-8) # Expected output: 'Invalid parameter type!'
find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0}) # Expected output: 'Invalid parameter type!'
find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
我不確定如何進行。我不確定如何檢查串列中的每種型別
uj5u.com熱心網友回復:
你在正確的軌道上;您只需要為型別比較創建一個回圈:
# (...)
else:
for num in l:
if type(num) not in (int, float):
return "Invalid parameter type!"
# (...)
uj5u.com熱心網友回復:
您可以嘗試以下代碼:
def find_negatives2(l):
l_tmp1 = []
if not isinstance(l, list):
return "Invalid parameter type!"
else:
for num in l:
if not (isinstance(num, float) or isinstance(num, int)):
return "Invalid parameter value!"
else:
if num < 0:
l_tmp1.append(num)
return l_tmp1
assert find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) == [-3.5, -2.7, -1.9]
assert find_negatives2([0, 1, 2, 3, 4, 5]) == []
assert find_negatives2(-8) == 'Invalid parameter type!'
assert find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0}) == 'Invalid parameter type!'
assert find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0]) == 'Invalid parameter value!'
assert find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0]) == 'Invalid parameter value!'
所有斷言都將被驗證。
解釋
isinstance檢查它的第一個引數是否是它的第二個引數的實體。使用此功能,您可以檢查任何變數型別。請注意,使用type(l) != list不是檢查變數型別的好方法。如果您有興趣了解原因,此鏈接可能會對您有所幫助。
uj5u.com熱心網友回復:
您可以通過以下方式實作您的目標:
def find_negatives(l):
if type(l) != list or any(str(x).isnumeric() for x in l) == False:
return 'Invalid parameter type!'
l_tmp = []
for num in l:
if num < 0:
l_tmp.append(num)
return l_tmp
您所要做的就是檢查輸入是否為串列以及輸入的任何元素是否不是數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429326.html
