我正在做一个练习,其中根据其主题和人数将某些班级划分为上级或下级。我可以对上层和下层类进行正确的分类,但是我的输出似乎是列表列表。下面是预期的输出,它只是一个列表。我的代码基于我到目前为止在模块中学到的方法。
预期产量
['PSYCH 412', 'MATH 300', 'MATH 404', 'ENG 201', 'PSYCH 508', 'ENG 220']
有人可以帮助我弄清楚如何将我的输出显示为列表而不是列表吗?谢谢。
classes = ["MATH 150", "PSYCH 111", "PSYCH 313", "PSYCH 412", "MATH 300", "MATH 404", "MATH 206", "ENG 100", "ENG 103", "ENG 201", "PSYCH 508", "ENG 220", "ENG 125", "ENG 124"]
upper = [] #empty list
lower = [] #empty list
for w in classes:
sub = w.split()
if "MATH" in sub and int(sub[1]) >= 300:
upper.append(sub)
elif "ENG" in sub and int(sub[1]) >= 200:
upper.append(sub)
elif "PSYCH" in sub and int(sub[1]) >= 400:
upper.append(sub)
else:
lower.append(sub)
print("Upper Level Courses:", upper)
我的输出
Upper Level Courses: [['PSYCH', '412'], ['MATH', '300'], ['MATH', '404'], ['ENG', '201'], ['PSYCH', '508'], ['ENG', '220']]
答案 0 :(得分:3)
您的解决方案已接近尾声,而不是将sub
附加w
到upper
或lower
:
classes = ["MATH 150", "PSYCH 111", "PSYCH 313", "PSYCH 412", "MATH 300", "MATH 404", "MATH 206", "ENG 100", "ENG 103", "ENG 201", "PSYCH 508", "ENG 220", "ENG 125", "ENG 124"]
upper = [] #empty list
lower = [] #empty list
for w in classes:
sub = w.split()
if "MATH" in sub and int(sub[1]) >= 300:
upper.append(w)
elif "ENG" in sub and int(sub[1]) >= 200:
upper.append(w)
elif "PSYCH" in sub and int(sub[1]) >= 400:
upper.append(w)
else:
lower.append(w)
print("Upper Level Courses:", upper)
打印:
Upper Level Courses: ['PSYCH 412', 'MATH 300', 'MATH 404', 'ENG 201', 'PSYCH 508', 'ENG 220']
答案 1 :(得分:0)
因为sub
对象是列表类型,所以在结果中它是列表。您可以将子列表集中为一个字符串,或者只使用w
对象,然后将其追加到上/下列表中。
classes = ["MATH 150", "PSYCH 111", "PSYCH 313", "PSYCH 412", "MATH 300", "MATH 404", "MATH 206", "ENG 100", "ENG 103", "ENG 201", "PSYCH 508", "ENG 220", "ENG 125", "ENG 124"]
upper = [] #empty list
lower = [] #empty list
for w in classes:
sub = w.split()
if "MATH" in sub and int(sub[1]) >= 300:
upper.append(" ".join(sub))
elif "ENG" in sub and int(sub[1]) >= 200:
upper.append(" ".join(sub))
elif "PSYCH" in sub and int(sub[1]) >= 400:
upper.append(" ".join(sub))
else:
lower.append(" ".join(sub))
print("Upper Level Courses:", upper)
您还可以使用List Comprehensions
来重写代码,如下所示:
classes = ["MATH 150", "PSYCH 111", "PSYCH 313", "PSYCH 412", "MATH 300", "MATH 404", "MATH 206", "ENG 100", "ENG 103", "ENG 201", "PSYCH 508", "ENG 220", "ENG 125", "ENG 124"]
upper = [c for c in classes if ("MATH" in c and int(c.split()[1])>=300) or ("ENG" in c and int(c.split()[1])>=200) or ("PSYCH" in c and int(c.split()[1])>=400) ]
lower = [c for c in classes if c not in upper]
希望有帮助。