我想编写一个函数来计算python中返回列表的Min-Max比例。
x = [1, 2, 3, 4]
def normalize(x):
for i in range(len(x)):
return [(x[i] - min(x)) / (max(x) - min(x))]
然后调用函数:
normalize(x):
结果:
[0.0]
我期待结果是:
[0.00, 0.33, 0.66, 1.00]
基于@ shehan的解决方案:
x = [1, 2, 3, 4]
def normalize(x):
return [round((i - min(x)) / (max(x) - min(x)), 2) for i in x]
print(normalize(x))
给你准确的你想要的。结果与其他解决方案不同(这就是你想要的)。
结果:
[0.0, 0.33, 0.67, 1.0]
对于答案的循环版本,操作可以理解:
x = [1, 2, 3, 4]
def normalize(x):
# A list to store all calculated values
a = []
for i in range(len(x)):
a.append([(x[i] - min(x)) / (max(x) - min(x))])
# Notice I didn't return here
# Return the list here, outside the loop
return a
print(normalize(x))
试试这个。
def normalize(x):
return [(x[i] - min(x)) / (max(x) - min(x)) for i in range(len(x))]
你除以max(x)
,然后减去min(x)
:
你也在反复重新计算max(x)
和min(x)
。你可以这样做:
x = [1, 2, 3, 4]
def normalize(x):
maxx, minx = max(x), min(x)
max_minus_min = maxx - minx
return [(elt - minx) / max_minus_min for elt in x]
您可以按照@ruturaj的建议对结果进行舍入,如果这是您要保留的精度:
return [round((elt - minx) / max_minus_min, 2) for elt in x]