简体   繁体   English

如何让我的代码读取特定行?

[英]How can i make my code read specific line?

beginner in python here, probably asking simple question. python 初学者在这里,可能会问一些简单的问题。 Basically I got an assigment that sounds like this.基本上我得到了一个听起来像这样的分配。 Each line in a.txt represents a question to which responders could respond with a,b,c (1,2,3 to simplify). a.txt 中的每一行代表一个问题,回答者可以用 a、b、c(简化为 1、2、3)来回答。 For example line 1 is: 1 2 1 1 3 3 .例如第 1 行是: 1 2 1 1 3 3 。 There are 3 questions(obv lines too).有 3 个问题(也有 obv 行)。 My assigment is to find out which answer is the most common for every question.我的任务是找出每个问题最常见的答案。 I wanted to make my code universal - a.txt can be modified with additional questions and answers.我想让我的代码通用 - a.txt 可以用其他问题和答案进行修改。 So far I got this:到目前为止,我得到了这个:

for l in range(sum(1 for line in open('a.txt'))):
  a, b, c = 0, 0 ,0
  with open("a.txt") as subor:
    o=[int(i) for i in subor.readline().split()]
    for k in range(len(o)):
      if o[k] == 3:
       c = c+1
      elif o[k] == 1:
        a = a + 1
      else:
        b = b + 1
    if a > b and a > c:
      print("In question", l + 1 ,'is answer A the most common one')
    elif c > b and c > c:
      print("In question", l + 1 ,'is answer C the most common one')
    elif a == b or a == c:
      print("Cannot be decided")
    else:
      print("In question", l + 1 ,'is answer B the most common one')
    a, b, c = 0, 0 ,0
    o.clear()

The code works, but it only finds the most common answer for the 1st question, it never moves to the next one.该代码有效,但它只能找到第一个问题的最常见答案,它永远不会移动到下一个问题。 How can i modify this code to move to the next question?如何修改此代码以转到下一个问题?

In the for loop every time you execute line with open("a.txt") as subor: you open again the file.每次在 for 循环中with open("a.txt") as subor:执行 line with open("a.txt") as subor:再次打开文件。 So you read the first line of the file with subor.readline() , then you re-open the file in the next iteration of the for loop.因此,您使用subor.readline()读取文件的第一行,然后在 for 循环的下一次迭代中重新打开该文件。 There are some errors also in the following part, I fixed them for you:以下部分也有一些错误,我为您修复了它们:

with open("a.txt") as subor:
    lines = subor.read().splitlines()

    l = 0
    for line in lines:

        o = [int(i) for i in line.split()]
        a = len([x for x in o if x == 1])
        b = len([x for x in o if x == 2])
        c = len([x for x in o if x == 3])

        if a > b and a > c:
            print("In question {} is answer A the most common one".format(l + 1))
        elif b > a and b > c:
            print("In question {} is answer B the most common one".format(l + 1))
        elif c > a and c > b:
            print("In question {} is answer C the most common one".format(l + 1))
        else:
            print("Question {} cannot be decided".format(l + 1))

        l += 1

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

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