Python字符串困难

2024-10-06 06:44:50 发布

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

我是python新手,我们刚刚开始研究字符串。这是一个我有点困难的问题。你知道吗

您将获得一个长字符串:

Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$

这根绳子有三条线。它包含三个学生的三门课程的分数。写一个函数findScore(student, subject)。当您调用诸如findScore(‘Drew’,’Java’)之类的函数时,该函数会打印“Drew got 75 of the course Java.”,除了findScore(student, subject)函数之外,您还可以编写其他函数。所有函数都在一个程序中。你知道吗

我本来想做这样的事,但是撞到墙了,哪里也去不了。我在python方面没有太多经验,所以可能有更好的方法。请帮忙。你知道吗

def findScore(student,subject):
  for i in string.split('$'):
    if student == Justin and subject == Calculus:
      JCalscore=90
    if student == Justin and subject == Java:
      JJavscore=85
    if student == Justin and subjext == Python:
      JPytscore=88  

Tags: and函数字符串ifjavastudentsubjectjustin
3条回答

当您调用string.split('$')时,您正在拆分整个字符串,而不仅仅是一行。另外,当您说student == Justinsubject == Calculus时,python试图找到一个名为JustinCalculus的变量。你知道吗

我建议使用交互式python解释器来尝试这些东西。你知道吗

   >>> a = '''
   ... Jstin$Calculus$90$Java$85$Python88$
   ... Taylor$Calculus$73$Java$95$Python86$
   ... Drew$Calculus$80$Java$75$Python94$
   ... '''

   >>> a.split('$')
   ['\nJustin', 'Calculus', '90', 'Java', '85', 'Python88', '\nTaylor', 'Calculus',
  '73', 'Java', '95', 'Python86', '\nDrew', 'Calculus', '80', 'Java', '75', 'Pyth
on94', '\n']
   >>> b = 'Justin'
   >>> if b == Justin:
   ...  print 'yes'
   ...
   Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  NameError: name 'Justin' is not defined
#!/usr/bin/env python

string = '''
Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$
'''

def findScore(student,subject) :
    global string
    students = [i for i in string.split('\n') if i]    # non-empty strings only
    for i in students :
        parts = i.split('$')
        if parts[0] == student :
            for j in range(1,len(parts),2) :
                if parts[j] == subject :
                    print student, 'got', parts[j+1], 'in', parts[j]

findScore( 'Justin', 'Java' )

欢迎使用堆栈溢出!我们很乐意帮助您解决任何编程问题。然而,我们不是家庭作业资源。你的大学无疑有这些。既然这个问题需要家庭作业方面的帮助,你就不会得到“即插即用”之类的答案。相反,我们将通过指出你给我们的事实,并提出引导性问题,来推动你朝着正确的方向前进。你知道吗

而且,你的问题似乎是重复的。在向我们提出问题之前,你应该认真考虑一下。你知道吗

首先,你的信息似乎被每个学生的空格/换行符分开了。似乎这些块中的每一个都包含一个人的信息,所以沿着这些线拆分可能是有意义的。如果您在课程中已经接触到classes,那么这里可能是一个考虑使用不同值存储相同类型信息的好地方。否则,您可能会考虑其他数据类型,例如listssetsdictionaries。你知道吗

似乎您想存储,您可以通过它们的名称查找这些值。Python内置的'dict'类型和'class'系统非常擅长这一点!或者,列表中课程名称和成绩的元组可以轻松执行相同的任务。你知道吗

相关问题 更多 >