我是python的新手,我有一个脚本,尝试使用Python 3.5运行它,但出现此错误
priorities[i].sort(cmp=comparer) TypeError: 'cmp' is an invalid keyword argument for this function
这是脚本中有错误的函数
def comparer(first, second):
"""Compare function for message priorities in maintenance mode"""
return cmp(int(first["Priority"]), int(second["Priority"]))
def get_sequence(inputs, fcm):
"""Creates right sequence for the maintenance mode"""
flags = count_flags(inputs)
sequence = []
for index, where in [(0, '"Axis"="Elevator"'),
(1, '"Axis"="Aileron"'),
(2, '"Axis"="Rudder" or "Axis"="HS-ACE"')]:
if len(flags[index]) == 0:
sequence += WRITE_SEQUENCE_MAINT_0.Get(where)
elif len(flags[index]) == 1:
sequence += WRITE_SEQUENCE_MAINT_1.Get(where)
elif len(flags[index]) > 1:
sequence += WRITE_SEQUENCE_MAINT_2.Get(where)
else:
raise NotImplementedError("This number of flags does not make sense")
priorities = [[], [], []]
for flag in flags[0] + flags[1] + flags[2]:
lines = WRITE_PROCESSING_MSGPRIORITY.Get('"Message Enable Flag"="%s" and "FCM Instance"="%s"' % (flag, fcm))
if len(lines) > 0:
priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[lines[0]["Axis"]]].append(lines[0])
for i in range(3):
priorities[i].sort(cmp=comparer)
for message in sequence:
if "Second Highest Priority" in message["Message"]:
new_m = priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[message["Axis"]]][1]
message["Message"] = new_m["Message"]
message["Lane"] = new_m["Lane"]
message["EP Bit"] = new_m["EP Bit"]
elif "Highest Priority" in message["Message"]:
priorities_for_rudder = priorities[{"Elev":0, "Ail":1, "Rud":2}[message["Axis"]]]
if len(priorities_for_rudder) > 0: # This rudder message does not exist
new_m = priorities_for_rudder[0]
message["Message"] = new_m["Message"]
message["Lane"] = new_m["Lane"]
message["EP Bit"] = new_m["EP Bit"]
else:
message["Message"] = "Rudder Filler Message"
message["Lane"] = "COM"
message["EP Bit"] = "0"
return sequence
此脚本是用python 2.7编写的。
答案 0 :(得分:1)
在python 3中不再有用于排序的cmp参数。
使用一个键和一个返回单个值以进行比较的函数。
您可以使用此功能代替比较器。
def comparer_key(item):
"""Compare keys for message priorities in maintenance mode. Returns a key."""
return int(item["Priority"])
然后
for i in range(3):
priorities[i].sort(key=comparer_key)