我一直在用这个功能打破我的头。
def snatch(data,threshold):鉴于我有以下数据:
data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] }
threshold = { 'x': 3, 'y': 2 }简单地说,数据字典的值应该合并为一个列表,如果它们高于或等于阈值的值。
X‘3,7的i.e. [3,7,7,3,2]高于或等于阈值'x’。对于'y‘3,7,2超过或等于阈值’‘。因此计算了平均值。
第二个条件是没有门槛。在这种情况下,相应的字母键被排除在列表之外,因此产品意味着。
例如thresh = { 'x': 3 },因此来自数据的列表仅为[3,7]
发布于 2022-11-06 22:16:09
使用这样的列表理解:
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发布于 2022-11-06 21:57:00
在不计算平均值的情况下,您只需遍历阈值项并链接满足条件的值。这就成了一条龙:
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://stackoverflow.com/questions/74340052
复制相似问题