python - 如何根据条件将列表转换为三个列表并放入字典中

标签 python list

我有这样的列表

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

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

最佳答案

我会这样做:

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

关于python - 如何根据条件将列表转换为三个列表并放入字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100149/

相关文章:

python - Django 中的上下文特定本地化

python - 如何在某些条件下制作一个 numpy 数组?

python - 编辑: Namespaces,和异常处理

python - 将变量名称分配给 if 语句 python 中的列表

c++ - 指向 const 数据和 C++ 列表的 const 指针

java - 使用重复的对象流式传输distinct()

python - 根据数据长度创建具有特定行为的循环

python - 通过 Image.fromarray 将 float 图像数组转换为 PIL 中的 int

c# - 如何在 C# 中使用列表创建循环

swift - 什么是元组和列表?