假設我有以下串列:
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = [0.4, 0.3, 0.6, 0.1, 0.9]
我想撰寫一個遍歷串列并按順序比較每個值的函式。
def compare_numbers(prob,thresh): output = [] for x, y in zip(prob, thresh): if x >= y: output.append(1) else: output.append(0) return output
compare_numbers(x,y)
這給了我型別錯誤: 'float' object is not iterable'
為什么是這樣?
我希望輸出看起來像這樣:
[1, 1, 0, 1, 0]
無論如何我可以撰寫這個函式,如果“閾值”值只有一位,它仍然可以作業嗎?
我目前制作后一個功能的代碼是:
def compare_numbers(prob, thresh): output = [] for n in prob: if n >= thresh: output.append(1) else: output.append(0) return output
compare_numbers(x,y)
然而,這會回傳型別錯誤:TypeError: '>=' not supported between instances of 'int' and 'list'當 thresh 是一個串列時。
uj5u.com熱心網友回復:
心理除錯:
您的第一個函式被傳遞給
floatorprob,thresh但代碼假定兩個輸入都是list(實際上,任何可迭代的)數字。您的第二個函式有相反的問題,它假設
thresh是一個標量值(例如float),但您將它作為list.
看起來你很困惑;您將第一個函式的引數傳遞給第二個函式,反之亦然。我不能確切地說它是如何出錯的,因為你沒有顯示足夠的資訊來說明你是如何呼叫函式的,但是回溯使最終問題變得顯而易見。
如果您想要一個接受以下任一功能的函式:
- 一個
float - 帶有一些浮點數的 A (如果太短
list,可以擴展以匹配)prob
對于thresh,你可以這樣做:
from itertools import cycle
def compare_numbers(prob,thresh):
try:
iter(thresh) # Check if it's iterable, so we can wrap if it's not
except TypeError:
thresh = (thresh,) # Convert float to one-tuple of float for compatibility later
output = []
for x, y in zip(prob, cycle(thresh)):
if x >= y:
output.append(1)
else:
output.append(0)
return output
回圈本身也可以是單行的:
return [int(x >= y) for x, y in zip(prob, cycle(thresh)]
或者:
return [1 if x >= y else 0 for x, y in zip(prob, cycle(thresh)]
為了簡單和小的性能提升。
uj5u.com熱心網友回復:
問題是您正在將 prob 中的值 n 與整個串列 thresh 進行比較。您需要做的是還迭代 thresh。這是一個小修復,可讓您的代碼正常作業:
def compare_numbers(prob, thresh):
output = []
for n in range(len(prob)):
if prob[n] >= thresh[n]:
output.append(1)
else:
output.append(0)
return output
uj5u.com熱心網友回復:
無論thresh是串列、元組還是單個值,這都應該有效:
def compare_numbers(prob,thresh):
if isinstance(thresh, (list, tuple)):
return [int(x >= y) for x,y in zip(prob,thresh)]
else:
return list(map(lambda x: int(x >= thresh), prob))
print(compare_numbers(x,y))
或者:
def compare_numbers(prob,thresh):
return [int(x >= y) for x,y in zip(prob, thresh)] if isinstance(thresh, (list, tuple)) else [int(x >= thresh) for x in prob]
輸出:
# list
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = [0.4, 0.3, 0.6, 0.1, 0.9]
[1, 1, 0, 1, 0]
# int or float
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = 0.4
[1, 1, 0, 0, 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522491.html
標籤:Python列表
