這個問題在這里已經有了答案: 如何從函式中獲取結果(輸出)?以后如何使用結果? (4 個回答) 14 小時前關閉。
我被要求提取值超過輸入閾值的字典日期。
請參閱下面的代碼:
def get_dates(prices,threshold):
{k:v for k,v in prices if threshold>130}
prc = [
{ 'price': 1279.79, 'date': '2020-01-01' },
{ 'price': 139.01, 'date': '2020-01-02' },
{ 'price': 134.3, 'date': '2020-01-03' },
{ 'price': 120.99, 'date': '2020-01-04' }
]
get_dates(prc, 130.0)
理想情況下,該函式應回傳價格超出閾值 (130) 的相應日期。但是,我的代碼沒有回傳任何內容。
uj5u.com熱心網友回復:
首先,您的函式中沒有 return 關鍵字。然后像這樣
def get_dates(prices, threshold) :
dates=[]
for dict in prices:
if dict['price']>threshold:
dates.append(dict['date'])
return dates
這將回傳一個日期陣列然后使用這個陣列
dates=get_dates(prc, 130)
uj5u.com熱心網友回復:
如果價格大于閾值,您可以使用list comprehensions并回傳s。dict
為什么 dict.get(key) 而不是 dict[key]?
# we use 'dict.get' with default value '0' for price if don't exists.
def get_dates(prices,threshold):
return [dct['date'] for dct in prices if dct.get('price', 0) > threshold]
prc = [
{ 'price': 1279.79, 'date': '2020-01-01' },
{ 'price': 139.01, 'date': '2020-01-02' },
{ 'price': 134.3, 'date': '2020-01-03' },
{ 'price': 120.99, 'date': '2020-01-04' }
]
get_dates(prc, 130.0)
輸出:
['2020-01-01', '2020-01-02', '2020-01-03']
uj5u.com熱心網友回復:
要回傳您想要的日期,請使用從上面date的每個 dict獲取鍵的串列理解:pricethreshold
def get_dates(prices,threshold):
return [d['date'] for d in prices if d['price'] > threshold]
prc = [
{ 'price': 1279.79, 'date': '2020-01-01' },
{ 'price': 139.01, 'date': '2020-01-02' },
{ 'price': 134.3, 'date': '2020-01-03' },
{ 'price': 120.99, 'date': '2020-01-04' }
]
print(get_dates(prc, 130.0)) # ['2020-01-01', '2020-01-02', '2020-01-03']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528176.html
標籤:Python字典
上一篇:提取和更改具有2個條件的字典項
