Python: 循环后输出错误

Python: wrong output after loop

我有两个列表:

coursestaken = ['COMP 1002', 'ECON 1020', 'ENGL 1110', 'MATH 1001', 'MATH 2050', 'BUSI 1101', 'MATH 2000', 'MATH 2050', 'OCSC 1000', 'STAT 2500', 'BUSI 1210', 'BUSI 1600', 'BUSI 3310', 'COMP 1003', 'BUSI 1000', 'COMP 1001', 'ECON 1010', 'ENGL 1090', 'MATH 1000']

course_grade_final = ['COMP 1002 Intro to Logic for Comp Sci B 65', 'ECON 1020 Intro to Macroeconomics A 89', 'ENGL 1110 Crtcl Rdng & Wrtng in Rhetori C 60', 'MATH 1001 Calculus II B 67', 'MATH 2050 Linear Algebra I F 44', 'BUSI 1101 Principles of Accounting A 89', 'MATH 2000 Calculus III A 80', 'MATH 2050 Linear Algebra I A 83', 'OCSC 1000 Exploration of World Ocean A 89', 'STAT 2500 Stats/Busi&Art Students I B 77', 'BUSI 1000 Intro to Business in Society B 78', 'COMP 1001 Intro to Programming B 69', 'ECON 1010 Intro to Microeconomics A 88', 'ENGL 1090 CRW: Telling Stories C 62', 'MATH 1000 Calculus I B 68']

我 运行 他们的这个循环应该检查 coursestaken 中的课程是否在 courses_grade_final 和 return 中按顺序排列,如果一门课程没有'没有成绩(正在进行中)它会跳过它:-

allcourses = []
for x in coursestaken:
    for y in course_grade_final:
        if x in y:
            allcourses.append(x)
            allcourses.append(y[-2:])
        else:
            continue

输出为:

['COMP 1002', '65', 'ECON 1020', '89', 'ENGL 1110', '60', 'MATH 1001', '67', 'MATH 2050', '44', 'MATH 2050', '83', 'BUSI 1101', '89', 'MATH 2000', '80', 'MATH 2050', '44', 'MATH 2050', '83', 'OCSC 1000', '89', 'STAT 2500', '77', 'BUSI 1000', '78', 'COMP 1001', '69', 'ECON 1010', '88', 'ENGL 1090', '62', 'MATH 1000', '68'] 

问题是 MATH 2050 由于某种原因翻了一番,我不明白为什么,正确的列表只有两个 MATH 2050,一个后面是 44,一个后面是 83。

image

您正在为 MATH 2050 的每个实例遍历整个列表,因此它会发现两次结果都是四个。

您可能只是想删除您在课程

中的额外'MATH 2050'

文本 MATH 2050 在第一次和第二次中被提及两次。因此,嵌套的 for 循环可为您提供 2 X 2 = 4 条匹配记录。

First List | Second List
-----------|------------------------------------
'MATH 2050'| 'MATH 2050 Linear Algebra I F 44')
'MATH 2050'| 'MATH 2050 Linear Algebra I A 83')

我没有完全了解你正在做的事情,但我猜你想做以下事情


>>> for x, y in zip(coursestaken, course_grade_final):
...     print((x, y[-2:]))
...
('COMP 1002', '65')
('ECON 1020', '89')
('ENGL 1110', '60')
('MATH 1001', '67')
('MATH 2050', '44')
('BUSI 1101', '89')
('MATH 2000', '80')
('MATH 2050', '83')
('OCSC 1000', '89')
('STAT 2500', '77')
('BUSI 1210', '78')
('BUSI 1600', '69')
('BUSI 3310', '88')
('COMP 1003', '62')
('BUSI 1000', '68')

>>> for x, y in zip(coursestaken, course_grade_final):
...     allcourses.append((x, y[-2:]))
...
>>> allcourses
[('COMP 1002', '65'), ('ECON 1020', '89'), ('ENGL 1110', '60'), ('MATH 1001', '67'), ('MATH 2050', '44'), ('BUSI 1101', '89'), ('MATH 2000', '80'), ('MATH 2050', '83'), ('OCSC 1000', '89'), ('STAT 2500', '77'), ('BUSI 1210', '78'), ('BUSI 1600', '69'), ('BUSI 3310', '88'), ('COMP 1003', '62'), ('BUSI 1000', '68')]

提示:

  1. 检查字符串函数,如 .startswith
  2. 检查python 正则表达式