Python: How to loop through blocks of lines

后端 未结 10 1368
青春惊慌失措
青春惊慌失措 2020-11-29 07:42

How to go through blocks of lines separated by an empty line? The file looks like the following:

ID: 1
Name: X
FamilyN: Y
Age: 20

ID: 2
Name: H
FamilyN: F
A         


        
10条回答
  •  青春惊慌失措
    2020-11-29 08:41

    simple solution:

    result = []
    for record in content.split('\n\n'):
        try:
            id, name, familyn, age = map(lambda rec: rec.split(' ', 1)[1], record.split('\n'))
        except ValueError:
            pass
        except IndexError:
            pass
        else:
            result.append((familyn, name, age))
    

提交回复
热议问题