dict - zip,列表生成式,三元运算
数据:
1,Alex Li,22,13651054608,IT,2013-04-01 2,Jack Wang,28,13451024608,HR,2015-01-07 3,Rain Wang,21,13451054608,IT,2017-04-01 4,Mack Qiao,44,15653354208,Sales,2016-02-01 5,Rachel Chen,23,13351024606,IT,2013-03-16 6,Eric Liu,19,18531054602,Marketing,2012-12-01 7,Chao Zhang,21,13235324334,Administration,2011-08-08 8,Kevin Chen,22,13151054603,Sales,2013-04-01 9,Shit Wen,20,13351024602,IT,2017-07-03 10,Shanshan Du,26,13698424612,Operation,2017-07-02
代码:
new_staff_table = {} filed_list = ['num','name','age','phone','dept','enroll_date'] def openfile(): staff_file = open("staffinfo.txt", 'r+', encoding='utf-8') for line in staff_file: line = line.strip().split(',') new_staff_table[line[1]] = dict(zip(filed_list,line[:6])) if __name__ == "__main__": openfile() print(new_staff_table)
new_staff_table = {} def openfile(): staff_file = open("staffinfo.txt", 'r+', encoding='utf-8') for line in staff_file: line = line.strip().split(',') new_staff_table[line[1]] = {'num':line[0],'name':line[1],'age':line[2],'phone':line[3],'dept':line[4],'enroll_date':line[5]} if __name__ == "__main__": openfile() print(new_staff_table)
结果:
{'Alex Li': {'num': '1', 'name': 'Alex Li', 'age': '22', 'phone': '13651054608', 'dept': 'IT', 'enroll_date': '2013-04-01'}, 'Jack Wang': {'num': '2', 'name': 'Jack Wang', 'age': '28', 'phone': '13451024608', 'dept': 'HR', 'enroll_date': '2015-01-07'}, 'Rain Wang': {'num': '3', 'name': 'Rain Wang', 'age': '21', 'phone': '13451054608', 'dept': 'IT', 'enroll_date': '2017-04-01'}, 'Mack Qiao': {'num': '4', 'name': 'Mack Qiao', 'age': '44', 'phone': '15653354208', 'dept': 'Sales', 'enroll_date': '2016-02-01'}, 'Rachel Chen': {'num': '5', 'name': 'Rachel Chen', 'age': '23', 'phone': '13351024606', 'dept': 'IT', 'enroll_date': '2013-03-16'}, 'Eric Liu': {'num': '6', 'name': 'Eric Liu', 'age': '19', 'phone': '18531054602', 'dept': 'Marketing', 'enroll_date': '2012-12-01'}, 'Chao Zhang': {'num': '7', 'name': 'Chao Zhang', 'age': '21', 'phone': '13235324334', 'dept': 'Administration', 'enroll_date': '2011-08-08'}, 'Kevin Chen': {'num': '8', 'name': 'Kevin Chen', 'age': '22', 'phone': '13151054603', 'dept': 'Sales', 'enroll_date': '2013-04-01'}, 'Shit Wen': {'num': '9', 'name': 'Shit Wen', 'age': '20', 'phone': '13351024602', 'dept': 'IT', 'enroll_date': '2017-07-03'}, 'Shanshan Du': {'num': '10', 'name': 'Shanshan Du', 'age': '26', 'phone': '13698424612', 'dept': 'Operation', 'enroll_date': '2017-07-02'}}
补充:
1.列表生成式 >>> li=[1,2,3] >>> [i*2 for i in li] [2, 4, 6] 2.三元运算 >>> a = True if 1 == 1 else False >>> a True >>> a = True if 1 == 2 else False >>> a False 3.zip() li1 = ["name","age"] li2 = ["pizza",18] >>> dict(zip(li1,li2)) {'name': 'pizza', 'age': 18} >>> list(zip(li1,li2)) [('name', 'a'), ('age', 'b')] >>> set(zip(li1,li2)) {('name', 'a'), ('age', 'b')} 4.步长 >>> li = [1,2,3,4,5] >>> li [1, 2, 3, 4, 5] >>> li[1:2] [2] >>> li[1:] [2, 3, 4, 5] >>> li[1::2] [2, 4]