D中的原始输入和阅读

2024-06-24 12:02:26 发布

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

我现在拥有的是:

f = open("SampleList.txt", "r")

x = f.readlines()
y = []


for i in range (len(x)):
  y.append(x[i].rstrip('\n').split(','))


for i in range(len(y)):
z = y[i]
print z

它的回报是:

['100000', 'Weasely ', 'Bill ', '9', '1 Discipline', '0']
['120001', 'Weasely ', 'Fred ', '10', '1 Discipline', '0']
['120002', 'Weasley ', 'George ', '6', '1 Tardies', '0']
['130003', 'Weasley ', 'Ronald ', '10', 'OK', '0']
['130004', 'Longbottom ', 'Neville ', '5', '1 Absence', '0']
['130005', 'Potter ', 'Harry ', '5', 'OK', '0']
['130006', 'MAlfoy ', 'Draco ', '5', '1 Owes more than $5', '$150.00']
['100118', 'The House Elf ', 'Dobbey ', '7', 'OK', '0']
['100011', 'LaStrange ', 'Belatrix ', '8', '1 Discipline', '0']
['100170', 'Dumbledore ', 'Albus ', '7', '1 Administration', '0']

我需要它知道的是,让一个学生输入一个原始的学生身份证号码,第一项是“10000”,以此类推。 然后它需要搜索并确定这个数字是否有效,如果它找到它打印出学生的名字的第一个和最后一个,如果他们是合格的,这是什么1纪律,1拖,如确定。 任何帮助都将不胜感激


Tags: intxtforlenrangeokopen学生
1条回答
网友
1楼 · 发布于 2024-06-24 12:02:26

读入文件内容时使用词典。你知道吗

字典的关键字是数据文件中的ID号(每行中紧随其后的第一个项),字典中的每个条目都将包含该行的其余部分作为list。你知道吗

def student_info(student):
    d = {}
    with open("SampleList.txt", "r") as f:
        x = f.readlines()

    for i in range (len(x)):
        ln = x[i].rstrip('\n').split(',')
        # Add this ID to the dictionary keys, and add the remainder of the line as the value for that key
        d[ln[0]] = ln[1:] 

    if student in d:
        return(d[student][1] + ' ' + d[student][0] + ' ' + d[student][-2])
    else:
        return 'invalid student id#'

studentID = raw_input('Enter your student ID#:  ')
print student_info(studentID)

相关问题 更多 >