编写Min-Max定标器功能

问题描述 投票:-1回答:3

我想编写一个函数来计算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] 
python data-science
3个回答
3
投票

基于@ 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))

1
投票

试试这个。

def normalize(x):
    return [(x[i] - min(x)) / (max(x) - min(x)) for i in range(len(x))]

1
投票

你除以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]
© www.soinside.com 2019 - 2024. All rights reserved.