jythonpython如何返回字符串的不同部分以获得分数

2024-05-15 09:43:52 发布

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

我该如何使用字符串和拆分来为列表中的三个特定的人从三个不同的分数中得到某个分数呢。这是单子。 贾斯汀:微积分90美元:Java$85:Python$88: 泰勒:微积分$73:Java$95:Python$86: 德鲁:微积分$80:Java$75:Python$94: 我现在被困在这件事上。我能找到的最好的例子就是这个。在

def phonebook():
  return """
Mary:893-0234:Realtor:
Fred:897-2033:Boulder crusher:
Barney:234-2342:Professional bowler:"""

def phones():
  phones = phonebook()
  phonelist = phones.split('\n')
  newphonelist = []
  for list in phonelist:
    newphonelist = newphonelist + [list.split(":")]
  return newphonelist
def findPhone(person):
  for people in phones():
    if people[0] == person:
      print "Phone number for",person,"is",people[1]

如你所见。问题是它只返回电话号码和他们的头衔。我需要做的是只返回一个类的名称和等级以及只有2个输入(名称、主题)的类。 这是我到目前为止的情况。在

^{pr2}$

是的,我是个新手。我已经找了好几天了。在


Tags: inforreturndefjavapeople分数list
1条回答
网友
1楼 · 发布于 2024-05-15 09:43:52

我建议使用字典。在

首先创建你的字典

students = {}

现在,为每一行创建一个学生

^{pr2}$

现在在学生字典中添加每个类作为关键字

for class_data in data[1:]:
    if class_data:
        class_name,class_score = class_data.split('$')
        students[name][class_name] = class_score

把它们放在一起你会得到:

students = {}
for studentdata in scores.split('\n'):
    data = studentdata.split(':')
    name = data[0]
    students[name] = {}
    for class_data in data[1:]:
        if class_data:
            class_name,class_score = class_data.split('$')
            students[name][class_name] = class_score

学生现在是字典的字典。找出与学生有关的分数 现在findScore是:

def findScore(student,subject):
    print "student %s got %s of the course %s" % (student,students[student][subject],subject)

不能保证学生和主语都在词典中,如果没有,就会出现错误。要防止出现这种情况,只需检查字典中是否有该键:

def findScore(student,subject):
    if student in students:
        if subject in students[student]:
            print "student %s got %s of the course %s" % (student,students[student][subject],subject)
        else:
            print "subject %s not found for student %s" % (subject,student)
    else:
        print "student %s not found" % (student)

现在,把它们放在一起,你会得到:

scores = """Justin:Calculus$90:Java$85:Python$88:
Taylor:Calculus$73:Java$95:Python$86:
Drew:Calculus$80:Java$75:Python$94:"""

students = {}
for studentdata in scores.split('\n'):
    data = studentdata.split(':')
    name = data[0]
    students[name] = {}
    for class_data in data[1:]:
        if class_data:
            class_name,class_score = class_data.split('$')
            students[name][class_name] = class_score

def findScore(student,subject):
    if student in students:
        if subject in students[student]:
            print "student %s got %s of the course %s" % (student,students[student][subject],subject)
        else:
            print "subject %s not found for student %s" % (subject,student)
    else:
        print "student %s not found" % (student)

#do some testing
findScore("Bob","Painting")
findScore("Taylor","Painting")
findScore("Taylor","Calculus")

关于字典(以及其他数据结构)的更多信息可以在here

相关问题 更多 >