实际上你不需要任何广告用于这样一个简单任务的模块。 Pure-Python解决方案将逐行读取文件并使用str.split()
对它们进行“解析”,它们将为您提供您的列表,然后您可以对任何参数进行非常多的过滤。喜欢的东西:
students = {} # store for our students by grade
with open("testdata.dat", "r") as f: # open the file
for line in f: # read the file line by line
row = line.strip().split("/") # split the line into individual columns
# you can now directly filter your row, or you can store the row in a list for later
# let's split them by grade:
grade = row[1] # second column of our row is the grade
# create/append the sublist in our `students` dict keyed by the grade
students[grade] = students.get(grade, []) + [row]
# now your students dict contains all students split by grade, e.g.:
a_students = students["A"]
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]
# if you want only to collect the A-grade student IDs, you can get a list of them as:
student_ids = [entry[0] for entry in students["A"]]
# ['1', '6']
但是,让我们回去了几步 - 如果你想你应该只存储您的列表,然后更广义的解决方案创建一个函数通过传递的参数进行过滤,所以:
# define a filter function
# filters should contain a list of filters whereas a filter would be defined as:
# [position, [values]]
# and you can define as many as you want
def filter_sublists(source, filters=None):
result = [] # store for our result
filters = filters or [] # in case no filter is returned
for element in source: # go through every element of our source data
try:
if all(element[f[0]] in f[1] for f in filters): # check if all our filters match
result.append(element) # add the element
except IndexError: # invalid filter position or data position, ignore
pass
return result # return the result
# now we can use it to filter our data, first lets load our data:
with open("testdata.dat", "r") as f: # open the file
students = [line.strip().split("/") for line in f] # store all our students as a list
# now we have all the data in the `students` list and we can filter it by any element
a_students = filter_sublists(students, [[1, ["A"]]])
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]
# or again, if you just need the IDs:
a_student_ids = [entry[0] for entry in filter_sublists(students, [[1, ["A"]]])]
# ['1', '6']
# but you can filter by any parameter, for example:
age_15_students = filter_sublists(students, [[2, ["15"]]])
# [['1', 'A', '15', '13', '43214'], ['2', 'I', '15', '21', '58322']]
# or you can get all I-grade students aged 14 or 15:
i_students = filter_sublists(students, [[1, ["I"]], [2, ["14", "15"]]])
# [['2', 'I', '15', '21', '58322'], ['5', 'I', '14', '4', '00000']]
所以我一直在玩到目前为止发布的不同解决方案。我喜欢你的解决方案。它将res显示为一组列表。我试图查找,而且我仍在搜索,但有没有办法将列表与列表分开?所以我可以基本上是水库的'A'级别列表,以及水库等的'C'级别?我所发现的只是将列表添加到集合中,或者从列表中删除列表,或者列表的子集和列表的子集。但我似乎无法找到任何有关多个列表的集合。 – chitown88