在中读取文件和编辑i的某些内容时出现问题

2024-09-28 03:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个
名字(空格)姓氏(制表符)等级

示例
万达理发师    96个

我很难将此作为列表读入,然后编辑号码

我现在的代码是

def TopStudents(n):

    original = open(n)
    contents = original.readlines()
    x = contents.split('/t')

    for y in x[::2]:
        y - 100 
        if y > 0: (????)

这就是我困惑的地方。我只是想知道得分超过100%的学生的名字和姓氏。我想为符合这个条件的学生建立一个新的名单,但我不确定如何写出相应的名字和姓氏。我知道我需要在列表中的每个其他位置上迈出一大步,因为名字和姓氏总是odd。提前感谢您的帮助


Tags: 代码编辑示例列表defcontents名字学生
2条回答

您的代码有几处错误:
-打开的文件必须关闭(#1)
-必须使用函数调用来调用它(#2)
-使用的拆分使用正斜杠(/)而不是反斜杠()(#3)
-如果您希望访问所有成员(#4),那么您决定在for循环中循环的方式不是最佳方式
-for循环以:(#5)
-您必须将计算结果存储在某个位置(#6)

def TopStudents(n):
    original = open(n) #1
    contents = original.readlines #2
    x = contents.split('/t') #3

    for y in x[::2] #4, #5
        y - 100 #6
        if y > 0:

也就是说,固定版本可以是:

original = open(n, 'r')
for line in original:
    name, score = line.split('\t')
    # If needed, you could split the name into first and last name:
    # first_name, last_name = name.split(' ')
    # 'score' is a string, we must convert it to an int before comparing to one, so...
    score = int(score)
    if score > 100:
        print("The student " + name + " has the score " + str(score))
original.close() #1 - Closed the file

注意:为了帮助您理解代码,我重点介绍了可读性和一些注释

我总是喜欢使用'with open()',因为它会自动关闭文件。为了简单起见,我使用了带有逗号分隔的txt,但是您可以将逗号替换为\t

def TopStudents():
    with open('temp.txt', 'r') as original:
        contents = list(filter(None, (line.strip().strip('\n') for line in original)))
    x = list(part.split(',') for part in contents)
    for y in x:
        if int(y[1]) > 100: 
            print(y[0], y[1])
TopStudents()

这将打开并将所有行作为列表加载到内容中,从而删除空行和换行符。然后它分成一个列表

然后遍历x中的每个列表,查找第二个值(y[1]),这是您的成绩。如果int()大于100,则打印y的每一段

相关问题 更多 >

    热门问题