我已经尝试了一些正确的功能,但我尝试的任何东西似乎都没有用。我想我有点想知道该做什么,但我试图做的却没有成功。所以我已经有了一个名为 string_avg(L)的函数,我认为我可以使用这个函数。 string_avg(L)由以下代码定义:
'''(list of str) -> list of list
Given a list of strings where each string has the format:
'name, grade, grade, grade, ...' return a new list of
lists where each inner list has the format :
[name (str), average grade (float)]
Requirement: This function should be 1 line long.
>>> string_avg(['Jo, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98'])
[['Jo', 86.0], ['Bill', 65.0], ['Cal', 98.0]]
'''
但现在我需要编写以下代码:
def string_avg_update(L):
'''(list of str) -> NoneType
Given a list of strings where each string has the format:
'name, grade, grade, grade, ...' update the given
list of strs to be a list of floats where each item
is the average of the corresponding numbers in the
string. Note this function does NOT RETURN the list.
>>> L = ['Jo, 50, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98']
>>> string_avg_update(L)
>>> L
[89.0, 65.0, 98.0]
'''
所以要获得string_avg_update(L),我可能会使用 string_avg(L)来给我[['Jo',86.0],['Bill',65.0],[' Cal',98.0]],然后从每个子列表中删除名称,并将每个列表中的剩余int加入到一个列表中。有没有办法做到这一点?我不知道如何删除列表中的第一个字符,但知道list.pop()删除列表中的最后一个字符,所以如果我使用list.reverse()将数字放在每个子列表中,我可以删除如果可能的话,命名然后将子列表加在一起。但是,使用list.reverse会反转子列表的顺序(即,Cal one优先),而不是反转每个子列表中的项目?是否有一种方法可以使每个列表都反转,所以我可以使用list.pop()(如果我可以弄清楚如何在每个子列表中使用它)。
或者有没有办法只删除列表中的字符串,以便我可以加入所有子列表,然后删除名称。 或者最好的想法可能是使用del从每个子列表中删除名称(即使用del list [0])但是我再一次不知道如何让del遍历每个子列表如果我将它用作del list [0],它将删除第一个子列表而不是每个子列表中的第一个字符。
我想这里的一个关键问题是如何将函数/方法应用于每个子列表而不是作为列表应用于子列表。
谢谢!
答案 0 :(得分:0)
字典可能是您尝试实现的更好的数据结构。 但是,这是一个适用于列表和一行限制的解决方案:
首先获得名称的平均值:
def av_grade(lst):
"""(list of str)->list of list
Given a list of strings where each string has the format:
'name, grade, grade, grade, ...' return a new list of
lists where each inner list has the format :
[name (str), average grade (float)]
Requirement: This function should be 1 line long.
>>> avg_grade(['Jo, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98'])
[['Jo', 86.0], ['Bill', 65.0], ['Cal', 98.0]]
"""
return [[x.split()[0], sum(map(float, x.split()[1:]))/(len(x.split()) - 1)] for x in ";".join(lst).replace(",", "").split(";")]
现在得到一个只有平均值的平面列表:
def av_grade_update(lst):
"""(list of str)->[float, float, ...]
Given a list of strings where each string has the format:
'name, grade, grade, grade, ...' return a new with the format :
[average grade (float), average grade (float)]
Requirement: This function should be 1 line long.
>>> avg_grade_update(['Jo, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98'])
[86.0, 65.0, 98.0]
"""
return [sum(map(float, x.split()[1:]))/(len(x.split()) - 1) for x in ";".join(lst).replace(",", "").split(";")]
请注意,这两个功能都在原始列表中运行。这是为了避免改变原始列表,因为一旦以您原来想要的方式进行变异,原始信息将不可逆转地丢失(至少在程序中)。