Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 这个代码简化了吗?我应该使用更多的功能吗?_Python_Python 3.4 - Fatal编程技术网

Python 这个代码简化了吗?我应该使用更多的功能吗?

Python 这个代码简化了吗?我应该使用更多的功能吗?,python,python-3.4,Python,Python 3.4,所以我正在开发这个程序,它打开一个外部文件,然后运行它,看看它是否包含特定的信息。有没有一种方法可以简化它,或者它现在是写这篇文章最有效的方法 def printGender(alist): if "Female" in alist: print(alist) print("Female Students") def maleInfo(blist): if "2010" in blist: print(blist)

所以我正在开发这个程序,它打开一个外部文件,然后运行它,看看它是否包含特定的信息。有没有一种方法可以简化它,或者它现在是写这篇文章最有效的方法

def printGender(alist):
    if "Female" in alist:
        print(alist)
        print("Female Students")

def maleInfo(blist):
    if "2010" in blist:
        print(blist)
        print("Students who enrolled in 2010")

def csc2010(clist):
   if "CSC" in clist and "2010" in clist and "Female" in clist:
        print(clist)
        print("Female students who registered in CSC in 2010")

def main():
    ref = open("file1.txt","r")

    studentList = ref.readlines()
    ask = 10
    while ask != 0:
    print("1) print all female info")
    print("2) display all male info from 2010")
    print("3) display female students who registered for CSC in 2010")
    ask = int(input("Enter option 1, 2, 3 or 0 to quit: "))
    if ask == 1:
        for i in range(len(studentList)):
            alist = studentList[i]
            printGender(alist)
    elif ask == 2:
        for i in range(len(studentList)):
            blist = studentList[i]
            maleInfo(blist)
    elif ask == 3:
        for i in range(len(studentList)):
            clist = studentList[i]
            csc2010(clist)
    elif ask == 0:
        print("You chose to quit")
        break
    else:
        print("Not a Valid input")
        continue

    ref.close()

main()
有没有办法简化这段代码,这样我就不会在main函数中创建三个单独的列表

    if ask == 1:
        for i in range(len(studentList)):
            alist = studentList[i]
            printGender(alist)
    elif ask == 2:
        for i in range(len(studentList)):
            blist = studentList[i]
            maleInfo(blist)
    elif ask == 3:
        for i in range(len(studentList)):
            clist = studentList[i]
            csc2010(clist)
    elif ask == 0:
        print("You chose to quit")
        break
    else:
    ect...

我很好奇,是否有一个更短的方法可以得到同样的结果。可能使用运行该部分代码的函数,但我不确定如何执行。

需要注意的一些问题:

  • 构造

    for i in range(len(studentList)):
        alist = studentList[i]
        printGender(alist)
    
    这是相当令人讨厌的;如果您确实需要
    i
    ,您应该使用

    for i, student in enumerate(student_list):
        print_gender(student)
    
    否则

    for student in student_list:
        print_gender(student)
    
  • 你的函数命名不好;他们说什么就做什么
    printGender
    打印女生,
    printMale
    打印2010年的学生,等等。同样,您的变量名选择不当<代码>列表不是学生列表,而是单个学生

  • 你似乎每个学生都有一个文本字符串,大概是
    20091176915,Jones,Susan,Female,CSC
    ;但是您没有尝试分离字段。这将导致学生出现恼人的问题,如2009年和2010年(学号错误匹配)、男女(姓氏错误匹配)以及CSC(课程名称错误匹配)中的学生,如2009年和2010年的学生。您确实需要使用更好的数据格式—无论是.csv或.json还是数据库,任何返回命名字段的格式—来解决这个问题

  • 您的搜索选项是非正交的,仅限于预先编码的选项;例如,如果不重写您的程序,您无法搜索2007年所有CSC学生

解决这些问题会导致您遇到类似的问题

import json

def record_print_format(record):
    return "{Year:4} {Id:6} {Gender:6} {Firstname:>20} {Lastname:<20} {Course:6}".format(**record)

def show_records(records, format_fn=record_print_format):
    for r in records:
        print(format_fn(r))
    num = len(records)
    print("{} records:".format(num))

def filter_records(records, field, value):
    return [r for r in records if r[field] == value]

def match_year(records, year):
    return filter_records(records, "Year", year)

def match_gender(records, gender):
    return filter_records(records, "Gender", gender)

def match_course(records, course):
    return filter_records(records, "Course", course)

def main():
    with open("student_list.json") as studentfile:
        all_students = json.load(studentfile)
        records = all_students

    while True:
        print("1: Filter by year")
        print("2: Filter by gender")
        print("3: Filter by course")
        print("8: Show results")
        print("9: Clear filters")
        print("0: Exit")

        option = input("Please pick an option: ").strip()

        if option == "1":
            year = input("Which year? ").strip()
            records = match_year(records, year)
        elif option == "2":
            gender = input("Which gender? [Male|Female] ").strip()
            records = match_gender(records, gender)
        elif option == "3":
            course = input("Which course? ").strip()
            records = match_course(records, course)
        elif option == "8":
            show_records(records)
        elif option == "9":
            records = all_students
        elif option == "0":
            print("Goodbye!")
            break
        else:
            print("I don't recognize that option.")

if __name__=="__main__":
    main()
导入json
def记录\打印\格式(记录):

return“{Year:4}{Id:6}{Gender:6}{Firstname:>20}{Lastname:这应该在代码审查中。我投票结束这个问题,因为它属于on,所以它是非主题的