如何正确使用double for循环?

时间:2019-01-14 18:18:58

标签: python-3.x loops for-loop

英国GSCE分级系统最近发生了变化,变得令人困惑,并且无法正常工作。我只是获得了估计的成绩,却不知道什么是好,什么不是。为了解决我的困惑,我决定进行一些保存,转换和编辑成绩的操作。为了使代码更整洁,我决定使用两个for循环,以便将它们全部打印出来。当我尝试此操作时,它看起来像在工作,但是它只是打印“对于英语,您得到6c”,然后当它转到本来是英语文学的内容时,它仅打印了“对于英语,您得到6c”,我确实获得了6c,但主题不是英语。如果我重新排列for循环的顺序,只有成绩相同,但课程是正常的,也会发生同样的情况。

我所做的只是重新排列了for循环。似乎没有任何作用。这是代码:

            import time

            with open('lessons.txt', 'r') as f:
                english_language = str(f.readline().strip('\n'))
                english_lit = str(f.readline().strip('\n\n'))
                maths = str(f.readline().strip('\n\n\n'))
                chemistry = str(f.readline().strip('\n\n\n\n'))
                physics = str(f.readline().strip('\n\n\n\n\n'))
                biology = str(f.readline().strip('\n\n\n\n\n\n'))
                re = str(f.readline().strip('\n\n\n\n\n\n\n'))
                business = str(f.readline().strip('\n\n\n\n\n\n\n\n'))
                computer_science = str(f.readline().strip('\n\n\n\n\n\n\n\n\n'))
                french = str(f.readline().strip('\n\n\n\n\n\n\n\n\n\n'))
                geography = str(f.readline().strip('\n\n\n\n\n\n\n\n\n\n\n'))

            lessons = []
            lessons.extend((english_language, english_lit, maths, chemistry, physics, biology, re, business, computer_science, french, geography))
            lesson_name = ["English langauge", "English liturature", "Maths", "Chemistry", "Physics", "Biology", "R.E", "Business studies", "Computer science", "French", "Geography"]

            print("What do you want to do? Read your grades, edit your grades, convert your grades or read and convert your grades.")
            option = input("Say read to read your grades or edit to edit your grades: ")

            if option == "read":
                for i in lessons:
                    for name in lesson_name:
                        print("For", name, "you got",i)
                        time.sleep(3)
                        break

            elif option == "convert":
                import converter.py

            elif option == "edit":
                print("HIIIIIIIIIIIIIIIIIIII")

文件中的等级范围从5B(我得到的最低)到7B(我得到的最高)。

我希望它做的是问您您想做什么,它做了什么。然后,如果您输入“读”,它会说“对于英语,您获得6c”并重复直到到达“地理”。

1 个答案:

答案 0 :(得分:-1)

两个for循环没有意义-中断也很奇怪:

for i in lessons:
    for name in lesson_name:
        print("For", name, "you got",i)
        time.sleep(3)     # 
        break             # this breaks after the first name every time

您可以使用类似的方法一次遍历两个列表:

nums = [1,2,3]
for idx,value in enumerate(["A","B","C"]):
     print("For", value, "you got", nums[idx])

或通过压缩将其压缩-参见下面的固定数据解析和后处理。


您可以通过忽略换行符来简化阅读,然后使用zip()将其余的成绩转换为字典:

创建一个包含换行符(且值太多)的文件

import random

gr = [ f'{num}{let}' for num in range(1,10) for let in "ABC"]

with open('lessons.txt', 'w') as f:
    for k in random.choices(gr,k=20):
        f.write(k+"\n\n\n")

读取文件并分解列表

with open('lessons.txt', 'r') as f:
    # read all lines, remove newlines, create a list of results
    grades = [x.strip() for x in f.readlines() if x.strip()]

# there are 20 scores in the file *_ takes all that are not named decomps: 

english_language, english_lit, maths, chemistry, physics, biology, re, \
business, computer_science, french, geography, *remainder = grades

print(english_language, english_lit, maths, chemistry, physics, biology, re, \
      business, computer_science, french, geography )

输出(3次运行):

3C 6A 9B 7B 8B 5A 2B 8C 7B 3A 9B
1C 8A 5A 1C 3A 9B 7C 9A 7B 7A 1A
4C 1A 4C 8B 9A 3C 2C 7B 7C 5B 2A

为课程和成绩创建查找字典:

您可以使用lesson_name将成绩与zip()关联:

# order the same as in the 
lesson_name = ["English langauge", "English liturature", "Maths", "Chemistry",
               "Physics", "Biology", "R.E", "Business studies", "Computer science", 
               "French", "Geography", "Remainder"]

# dict comprehension to build the dictionary mapping lesson names to grades
grades = {k:v for k,v in zip(
    lesson_name,
    [english_language, english_lit, maths, chemistry, physics, biology, re,  
     business, computer_science, french, geography, remainder])}

print (grades) 

输出:

{'English langauge': '4B', 'English liturature': '3C', 'Maths': '1C', 
 'Chemistry': '8C', 'Physics': '6B', 'Biology': '2B', 'R.E': '6C',
 'Business studies': '8C', 'Computer science': '4B', 'French': '3A', 
 'Geography': '2A', 
 'Remainder': ['7B', '1A', '1C', '3B', '2B', '8B', '5B', '6B', '8C']}

您可以使用dict通过名称查找成绩:

print(grades["English langauge"]) # 4B

要打印所有内容:

for name, grade in grades.items():
    print("For", name, "you got", grade) 
    # do not break here- this will end the loop!

一些解释:

grades = [x.strip() for x in f.readlines() if x.strip()]

整个列表comp会读取文件的所有行,丢弃空行和仅包含空格(空格,制表符,换行符..)的行-其余行被放入列表False中,但被剥离首先,所以没有任何开始/结束空格。

  • zip()接受多个可迭代对象,并将它们配对为元组-只要ans最短,则可迭代对象为:

grades

导致:

k = zip( [1,2,3],["a","b"],"!$&(=" )  #  [(1, 'a', '!'), (2, 'b', '$')]

将其应用于您的数据,我将您的单个成绩列表和(1, 'a', '!') # every 0th element (2, 'b', '$') # every 1st element and nothing more because ["a","b"] has no 2nd element 的“字符串”压缩在一起以得到:

lecture_names

并在字典理解中使用它来创建字典:

[('English langauge', '5B'), ('English liturature', '8B'), ('Maths', '1C'), 
 ('Chemistry', '4B'), ('Physics', '4C'), ('Biology', '9A'), ('R.E', '6B'), 
 ('Business studies', '8A'), ('Computer science', '1A'), ('French', '8C'), 
 ('Geography', '9B'), 

 ('Remainder', ['7A', '4C', '6C', '5B', '3B', '9C', '3B', '1A', '3B'])]

grades = {k:v for k,v in zip( lesson_name, [english_language, english_lit, maths, chemistry, physics, biology, re, business, computer_science, french, geography, remainder])} k是一个zip-result-tuple的分解-dict理解会根据它们创建字典:

v

ex = {k:v for k,v in [ ("a",1), ("b",2) ] } # simplified example 作为字典ex返回。

HTH