繁体   English   中英

如何在while循环中使用for循环访问数组

[英]How do I access the array using the for loop in the while loop

我正在使用一个外部文件,该文件的数据格式为:

-12345 CSEE 35000巴特·辛普森

-12346 CSEE 25000哈利·波特

-12350经济学30000克鲁斯小丑

-13123经济学55000 David Cameron

第一项是ID,第二项是科目,第三项是薪水,其余项是此人的姓名。

在我的程序的一部分中,我尝试打印薪水介于用户提交的值之间的人员的信息。 我将所有数据都放在一个名为“讲师”的列表中,然后将所有薪水放在一个单独的列表中,称为“讲师的工资”,并试图使它们成为整数,因为起初我认为for循环不起作用的原因是因为在尝试访问时他们从讲座循环中发现,我认为此时它们仍可能是字符串的一部分。

我已经在程序中使用循环来打印所有教授特定主题的人。 该主题由用户提交。 我试图再次为工资使用for循环,但是它不起作用。

print""

# To God be the Glory

lecturer = []
lecturer_salary = []

x = 0
a = " "

print ""
String = raw_input("Please enter the lecturers details: ")
print ""

def printFormat(String):
    String = String.split()
    lastname = String[-1]
    firstnames = " ".join(String[3:-1])
    name = ", ".join([lastname, firstnames])

    ID_Subject = " ".join(String[0:2])
    money = String[2]

    print "%s,%s    %s    %s" % (lastname,firstnames,ID_Subject,money)

printFormat(String) 

while x < len(lecturer):
    lecturer_salary.append(int(lecturer [x][2]))
    x = x + 1 

print ""

try:  
    fname = input("Enter filename within " ": ")

    with open(fname) as f:
        for line in f:
            data = line.split()
            printFormat(line) 
            line = line.split()
            lecturer.append(line)         

except IOError as e :
    print("Problem opening file")

print ""
print ""



answer = raw_input("Would you like to display the details of lectureers     from a particular department please enter YES or NO: ")

if answer == "YES" :
    print ""
    department = raw_input("Please enter the department: ")
    print ""

    while x < len(lecturer) :

        for line in lecturer:

            if lecturer[x][1] == department:
                a = lecturer[x]
                a = ' '.join(a)
                printFormat(a)

            x = x + 1




**elif answer == "NO" :
    print ""
    answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")

    print ""

    if answer2 ==  "YES":

        lower_bound = int(input("Please enter the lower bound of the salary range: "))
        upper_bound = int(input("Please enter the upper bound of the salary range: "))

        print ""

        while x < len(lecturer) :

            for line in lecturer_salary:

                if lower_bound < lecturer_salary[x] < upper_bound :

                    print lecturer_salary[x]

                x = x + 1**


else:
    print ""
    print "Please enter a valid input"

因此,您有一组讲师和一名讲师薪水。

for line in lecturer_salary:

不需要-稍一会儿再加上if。 请注意,这只会打印出薪水,而不会显示讲师的详细信息。 由于x是两个数组的索引,因此您可以访问其余的讲师[x]。 实际上,您根本不需要讲师工资,只需遍历讲师并检查:

while x < len(lecturer) :
    if lower_bound < lecturer[x][2] < upper_bound :
        a = lecturer[x]
        a = ' '.join(a)
        printFormat(a)
    x = x + 1

对于初学者,您不应使用StringId_Subject这样的大写字母来命名变量。

将代码分解为函数并尝试使用字典或类来提高可读性和可扩展性会更简单。

这是使用类的最少代码:

lecturers = [] # To store Lecturer instances, which isn't necessary                                                                                     

class Lecturer():
    def __init__(self, id, subject, salary, name):
        self.id      = id
        self.subject = subject
        self.salary  = salary
        self.name    = name

def readfile(filename):
   """read each line in a file and yield a list of fields"""
    with open(filename, "r") as f:
        for line in f.readlines():
            # return a list of fields                                                                                             
            yield line.replace("\n", "").split()

def new_lecturer(detail):
    """Return a new lecturer instance from a list of fields"""
    return Lecturer(detail[0],
                    detail[1],
                    detail[2],
                    {"firstname": detail[3],
                     "lastname": detail[4]
                    })

def print_lecturer_detail(lecturer):
    """Accept a lecturer instance and print out information"""
    print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
                                   lecturer.name["firstname"],
                                   lecturer.id,
                                   lecturer.salary)

def main():
    """This is where all the main user interaction should be"""
    fname = raw_input("Enter filename: ")
    for lecturer in (readfile(fname)):
        lecturers.append(new_lecturer(lecturer))
    print ""

    answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")

    if answer == "Y":
    print ""
        department = raw_input("Please enter the department: ")
        print ""

        for lecturer in lecturers:
            if lecturer.subject == department:
                print_lecturer_detail(lecturer)

    elif answer == "N":
        # implement salary code here                                                                                              
        pass

if __name__ == '__main__':
    main()

现在这可能是一个矫kill过正的做法,但是它比长期处理列表要好。 您将看到处理属性变得更加简单。 您可能需要进一步改进每个功能,使其更具模块化和可重用性。

@保罗Morrington对直答案while一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM