【发布时间】:2017-10-11 22:22:29
【问题描述】:
我真的在为编写 python 代码而苦苦挣扎。任何帮助将不胜感激。我需要编写代码的功能如下。由于数字是输入中的字符串,我知道我不能以某种方式按学生的姓名分开,我想我必须以某种方式将数字转换为 int/float,然后以某种方式按名称将列表分成子列表(即按字符串) 但我不知道如何做到这一点。我知道我可以使用 map(int, ) 将某些内容转换为 int,但它似乎不起作用,并且等级数(即我需要转换为浮点数)可能因任何输入而异
谢谢!
代码:
def string_list(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), grade, grade, grade, ...] where the name
is a string and the grades are floats.
>>> string_list(['Joe, 60, 90, 80', 'Harry, 60, 70', 'Jill, 98.5, 100, 95.5, 98'])
[['Joe', 60.0, 90.0, 80.0], ['Harry', 60.0, 70.0], ['Jill', 98.5, 100.0, 95.5, 98.0]]
'''
【问题讨论】:
-
尝试分解问题。你会得到一个大字符串,其中包含姓名和成绩。你怎么能把这些碎片分开? (提示:查看输入字符串的格式!)
-
感谢您的提示!每个人的名字和他们的成绩都是一个单独的字符串,所以我会看看我是否可以以某种方式拆分这些字符串中的每一个,然后从那里将数字转换为 int。
-
为了好玩(并提醒您我们在 Python 中使用它是多么容易......)我 implemented this in Haskell。公平地说,我确实重新实现了
Data.Text包中存在的splitOn和strip。我打算没有导入,但发现定义Data.Char(isSpace)是……乏味的。
标签: python python-3.x