我如何创建一个函数,例如normalist(x,y),它返回一个数字列表,它是' x',规范化,以便规范化列表的总和为1.0并填充以包含& #39; 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].`
我不知道如何进行填充,我试图使用normalist(x,y),因此我可以针对任何列表运行该函数。
def normalist():
list = [2, 2, 2, 2]
s = sum(list)
norm = [float(i)/s for i in list]
return norm
print(normalist())
答案 0 :(得分:1)
如何规范化列表:
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)
个他们。 len()
我们还检查lst
的大小是否小于或等于n
,请更改此项,但希望您的功能正常运行。
答案 1 :(得分:1)
首先,让我们直接得到参数:
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 已经足够长,这将无效。