在不了解数据来源的更多细节的情况下,我可能会考虑使用namedtuple
是否可以更改data
存储方式的结构。它将使事情变得更干净,更具可读性。
这是一个例子:
>>> from collections import namedtuple
>>> Record = namedtuple('Record', ['date', 'id', 'code', 'status'])
>>> records = []
>>> records.append(Record('08132012', 'id01', '02343','P'))
>>> records.append(Record('08132012', 'id01', '03343','F'))
>>> records.append(Record('08132012', 'id02', '18131','F'))
>>> records.append(Record('08132012', 'id02', '07777','F'))
>>> for record in records:
... print "Date: %s" %record.date
... print "Processing id: %s" %record.id
... print record.code
... print record.status
...
Date: 08132012
Processing id: id01
02343
P
Date: 08132012
Processing id: id01
03343
F
Date: 08132012
Processing id: id02
18131
F
Date: 08132012
Processing id: id02
07777
F
更多乐趣:
获取status
'F' 所在的记录列表:
>>> Fs = [record for record in records if record.status == 'F']
>>> Fs
[Record(date='08132012', id='id01', code='03343', status='F'),
Record(date='08132012', id='id02', code='18131', status='F'),
Record(date='08132012', id='id02', code='07777', status='F')]
排序方式code
:
>>> records.append(Record('08122012', 'id03', '00001', 'P'))
>>> records.sort(key=lambda x:x.code)
>>> records
[Record(date='08122012', id='id03', code='00001', status='P'),
Record(date='08132012', id='id01', code='02343', status='P'),
Record(date='08132012', id='id01', code='03343', status='F'),
Record(date='08132012', id='id02', code='07777', status='F'),
Record(date='08132012', id='id02', code='18131', status='F')]