我在一个文本文件的单独行中列出了很多天的出席情况,一周中的日期后跟一个逗号,然后是以逗号分隔的参加者的名字,例如星期一,简,约翰,乔,玛丽。
我需要找到并打印出最多学生和参加人数的学生。
rgb
答案 0 :(得分:1)
假设你的.txt文件有像这样的出勤细节
Monday, Jane, John, Joe, Mary
Tuesday, Jane, John, Joe, Mary
Wednesday, Jane, John, Joe, Mary, Dave1, Dave2
Thursday, Jane, John
Friday, Jane, John, Joe, Mary, Dave
Saturday, Jane
Sunday, Jane, John, Joe, Mary, Dave
Monday, Jane, John, Joe
然后,我们打开文件,将每一行作为字符串附加到名为attendanceList
的列表中。
attendanceList = []
file = open('/Users/abhi/Desktop/attendance.txt', 'r') #Enter your file path here
for line in file:
attendanceList.append([line])
然后我们进入字符串列表的列表,并将其拆分为逗号,这样我就可以找回另一个正确逗号分隔的列表(这一步可以在上面完成,但我是故意将它分开
newList = []
for i in attendanceList:
for j in i:
new = j.split(",")
newList.append(new)
print(newList)
现在,您将拥有表单中的列表,[[day1
,name1,
name2 , ..], [
day2 ,
name1,name2
,{{1} },..]
下面的行只是选择列表中最大长度为
的列表name3
由于最大元素列表中的第一个元素将始终代表该日
maxStudents = max(newList, key = len)
print("\n")
print(maxStudents)
学生人数将等于day = maxStudents[0]
列表的长度 - 1,因为第一个元素代表maxStudents
day