我一直在用這個功能打破我的腦袋。
def snatch(data,threshold):
鑒于我有以下資料:
data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] }
threshold = { 'x': 3, 'y': 2 }
簡而言之,如果資料字典的值高于或等于閾值,則它們應該合并為一個串列。
i.e. [3,7,7,3,2]對于“x”,3,7 高于或等于閾值“x”。對于“y”,3,7,2 高于或等于閾值“y”。因此計算平均值。
第二個條件涉及沒有閾值。在這種情況下,相應的字母鍵被排除在串列之外,因此產品的意思。
例如 thresh = { 'x': 3 },因此資料串列僅[3,7]
uj5u.com熱心網友回復:
使用這樣的串列推導:
def snatch(data, threshold):
return [v for k in threshold for v in data[k] if v >= threshold[k]]
本質上,上面的函式是這樣做的:
def snatch(data, threshold):
snatched = []
for key in threshold:
for value in data[key]:
if value >= threshold[key]:
snatched.append(value)
return snatched
uj5u.com熱心網友回復:
在不計算平均值的情況下,您只需遍歷閾值項并將滿足條件的值鏈接起來。這變成了一個單行:
from itertools import chain
def snatch(data, threshold): return list(chain(*[[a for a in data[k] if a >= v] for k, v in threshold.items()]))
data = {'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2]}
threshold = {'x': 3, 'y': 2}
print(snatch(data, threshold))
# [3, 7, 3, 7, 2]
并且僅使用一些鍵可以得到所需的結果:
thresh = {'x': 3}
print(snatch(data, thresh))
# [3, 7]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528175.html
標籤:Python字典条件语句
