我有一個包含 2 個值的串列。我想將這些值與 3 個范圍(lotSize)進行比較——每個范圍都有一個與之關聯的值——所以最終我希望能夠在 2 個值之一落入 5 個范圍中的任何一個時參考這個最終值。
要比較的 2 個值:
countList = [150,250]
目前我有一個范圍值串列,例如
lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30},]
我不知道如何查看 countList 中的值是否在某個范圍內,如果為真,則獲取“finalValue” - 我想這里需要一個 for 回圈?
uj5u.com熱心網友回復:
countList = [150,250,1000]
lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30},]
def get_fv(cl):
fv =[]
for c in cl:
for ls in lotSize:
r = ls['range']
if c in r:
fv.append(ls['finalValue'])
else:
print(f"No range found for {c}")
return fv
print(get_fv(countList))
輸出:
No range found for 1000
[10, 20]
uj5u.com熱心網友回復:
You can create a function that maps one entry in countList to a final value, then use map() and list() to repeat this for every element in countList:
def get_final_value(item, lotSize):
for entry in lotSize:
if item in entry['range']:
return entry['finalValue']
raise ValueError(f"{item} is in not any of the ranges")
countList = [150,250]
lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30}]
result = list(map(lambda x: get_final_value(x, lotSize), countList))
print(result) # Prints [10, 20]
uj5u.com熱心網友回復:
The easiest approach that came to my mind is what follows:
[y["finalValue"] for y in lotSize for x in countList if x in y["range"]]
Output
[10, 20]
But note that, this will results in duplicates if you both countSize values exist in the range key. In this case, you just need to transform it to set and then transform it to list in order to remove the duplicates.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/443154.html
