规范化和0填充

2024-04-20 08:14:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何创建一个函数,例如normalist(x,y),它返回一个“x”的数字列表,规格化后的列表的总和为1.0,并填充为包含“y”元素。例如

normalist([2,2,2,2,2], 5) => [0.2, 0.2, 0.2, 0.2, 0.2]
normalist([5], 4)         => [1.0, 0.0, 0.0, 0.0].`

我不知道如何进行填充,我正在尝试使正规(x,y),这样我就可以对任何列表运行函数。你知道吗

def normalist():

    list = [2, 2, 2, 2]
    s = sum(list)
    norm = [float(i)/s for i in list]
    return norm

print(normalist())

Tags: 函数in元素norm列表forreturndef
2条回答

如何规范您的列表:

def normalist(lst):
    s = sum(lst)
    norm = [float(i)/s for i in lst]
    return norm

lst = [2, 2, 2, 2]
print(normalist(lst))

注意我们传递的是lst,而不是在函数中硬编码它。也不要给变量命名关键字,比如list。Python允许这样做,但是它覆盖了一些函数。你知道吗


添加了一些0.0填充:

def normalist(lst, n):
    if len(lst) > n:
        print('length of list is bigger than n')
        return False
    s = sum(lst)
    norm = [float(i)/s for i in lst] + [0.0]*(n-len(lst))
    return norm

lst = [2, 2, 2, 2]
n = 5
print(normalist(lst,n))  #outputs [0.25, 0.25, 0.25, 0.25, 0.0]

在Python中,我们可以使用+将列表追加或添加到一起,[0.0]*(n-len(lst))基本上是说:我想要一个0.0的列表,我想要其中的n - len(lst)个数。^{}我们还检查lst的大小是否小于或等于n,如果希望函数正常工作,请更改此值。你知道吗

首先,让我们把参数弄清楚:

def normalist(in_list, n):

    s = sum(in_list)
    norm = [float(i)/s for i in in_list]
    return norm

print(normalist([4, 5, 2, 5], 4))

输出:

[0.25, 0.3125, 0.125, 0.3125]

现在,要填充,只需将n与列表的长度进行比较:

for extra in range(len(norm), n+1):
    # append a 0 to norm

请注意,如果norm已经足够长,则这将不起任何作用。你知道吗

相关问题 更多 >