我已将所有对象添加到列表中但它们没有排序,我想通过LevelNo对列表中的条目进行排序,所以1然后是两个。
我得到的错误是
Traceback (most recent call last):
File "pagerduty.py", line 143, in <module>
OnCallData = OnCallData.sort(key=operator.itemgetter('LevelNo'))
NameError: name 'operator' is not defined
我目前的代码是
from operator import itemgetter
class User(object):
__attrs = ['Policy','Level', 'LevelNo', 'StartDate', 'EndDate', 'StartTime',
'EndTime', 'Name', 'Mobile']
def __init__(self, **kwargs):
for attr in self.__attrs:
setattr(self, attr, kwargs.get(attr, None))
def __repr__(self):
return ', '.join(
['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])
OnCallData = []
for UserItem in objPolicyData['users']:
UserData = User()
UserData.Name = UserItem['name']
UserData.Mobile = UserMobile = getUserMobile(UserItem['id'])
for OnCall in UserItem['on_call']:
UserPolicy = OnCall['escalation_policy']
PolicyName = UserPolicy['name']
if PolicyName.lower().find('test') == -1:
UserData.Policy = PolicyName
UserData.LevelNo = OnCall['level']
UserData.Level = getLevel(OnCall['level'])
UserData.StartDate = getDate(OnCall['start'])
UserData.EndDate = getDate(OnCall['end'])
UserData.StartTime = getTime(OnCall['start'])
UserData.EndTime = getTime(OnCall['end'])
OnCallData.append(UserData)
OnCallData = sorted(OnCallData, key=itemgetter('LevelNo'))
样本数据
[
Policy: u'Network Team', Level: 'Backup On Call Engineer', LevelNo: 2, StartDate: 'Monday 02 May', EndDate: 'Monday 09 May', StartTime: '09:00AM', EndTime: '09:00AM', Name: u'John Smith', Mobile: u'07XXX',
Policy: u'System Administator Team', Level: 'Primary On Call Engineer', LevelNo: 1, StartDate: 'Tuesday 03 May', EndDate: 'Tuesday 03 May', StartTime: '09:00AM', EndTime: '05:00PM', Name: u'Billy Bones', Mobile: u'07XXX',
Policy: u'Network Team', Level: 'Primary On Call Engineer', LevelNo: 1, StartDate: 'Friday 29 April', EndDate: 'Tuesday 03 May', StartTime: '05:00PM', EndTime: '03:30PM', Name: u'Jim Bob', Mobile: '07XXX'
]
答案 0 :(得分:1)
您需要导入itemgetter
。首先将from operator import itemgetter
添加到代码顶部。
答案 1 :(得分:1)
我认为这也应该有用
>>> sorted(a, key=lambda x: x['b'])
[{'a': 1, 'c': 2, 'b': 3}, {'a': 1, 'c': 2, 'b': 4}]
>>>
PS:我使用虚拟数据,因为你的数据不是正确的python结构。
在你的情况下,它将是
_OnCallData = sorted(OnCallData, key=lambda x: x.LevelNo)
答案 2 :(得分:0)
这应该有效。
def update(): #This defines the update procedure
input_file=open("Scores.txt","r")
name=input("Enter name") #Uses variable to store name that is asked for
highScore=input("Enter current high score")
newHighscore=input("Enter new high score")
data=input_file.read().splitlines()
input_file.close
position=0 #Placing of the data at the start
found=False