1

我有这样的清单

mylist = [student_number , student_age , student_marks , subject_name , subject_marks, subject_date , ass_name , ass_number]

我想要类似的东西

   list_student = [student_number , student_age , student_marks]
   list_subject = [subject_name , subject_marks, subject_date]
   list_ass     = [ass_name , ass_number]

以便它与下划线之前的文本匹配,将其作为字典的键

我想将其转换为字典,以便我可以访问类似

 for a AllList['student']:
           Student stuff

编辑:列表元素可以按任何顺序排列

4

3 回答 3

2

我会这样做:

# Build dictionary with prefix:list pairs
targets = {
    'student_': [],
    'subject_': [],
    'ass_': []
}

for i in mylist:
    # Try to find matching prefix
    for prefix in targets:
        if i.startswith(prefix):
            targets[prefix].append(i)
            break

这将很容易让您添加更多前缀并且不关心顺序。

假设(这些值是字符串):

mylist = ['student_number', 'student_age', 'student_marks', 'subject_name',
          'subject_marks', 'subject_date' , 'ass_name' , 'ass_number' ]

你会得到这样的结果:

>>> for i in targets: print( i, targets[i])
...
ass_ ['ass_name', 'ass_number']
student_ ['student_number', 'student_age', 'student_marks']
subject_ ['subject_name', 'subject_marks', 'subject_date']
于 2013-04-19T08:19:00.797 回答
1

作为替代方案,您可以使用collections.defaultdict

from collections import defaultdict

mylist = ['student_number', 'student_age', 'student_marks', 'subject_name',
      'subject_marks', 'subject_date' , 'ass_name' , 'ass_number' ]


d = defaultdict(list)
for v in myList:
    k = v.split('_')[0]
    d[k].append(v)

它会给你:

>>>print d
defaultdict(<type 'list'>, {'ass': ['ass_name', 'ass_number'], 'student': ['student_number', 'student_age', 'student_marks'], 'subject': ['subject_name', 'subject_marks', 'subject_date']})
于 2013-04-19T08:33:50.280 回答
0

这是我的解决方案:

>>> mylist = ['student_number', 'student_age', 'student_marks', 'subject_name',
...           'subject_marks', 'subject_date' , 'ass_name' , 'ass_number' ]
>>> import itertools
>>> m = {k:list(v) for k,v in itertools.groupby(mylist, lambda s: s.split('_')[0])}
>>> m
{'ass': ['ass_name', 'ass_number'], 'student': ['student_number', 'student_age', 'student_marks'], '
subject': ['subject_name', 'subject_marks', 'subject_date']}
于 2013-04-19T08:51:14.600 回答