【问题标题】:Raw Input and Reading in Data原始输入和数据读取
【发布时间】:2016-02-02 13:19:15
【问题描述】:

我目前拥有的是:

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']

我需要它知道的是要求学生输入他们的学生 ID 号的原始输入,即第一项“10000”等等。 然后它需要搜索并确定该号码是否有效,如果找到它打印出学生的名字和姓氏,以及他们是否符合条件,这就是 1 Discipline,1 Tardies,就像 OK。 任何帮助将不胜感激

【问题讨论】:

  • 多比名字里没有e...
  • 当我们在命名时,它是 Bellatrix Lestrange。
  • 提示:for z in y: print z[0] 打印什么?

标签: python


【解决方案1】:

读取文件内容时使用字典。

字典被键入到数据文件中的 ID 号(每行中的第一项在您 split 之后),并且字典中的每个条目将包含该行的其余部分作为 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多