sorted()在Windows系统上获取语法错误

时间:2017-07-30 09:17:03

标签: python python-3.x

class Employee():
def __init__(self, name, age, salary):
    self.name = name
    self.age = age
    self.salary = salary

def __repr__(self):
    return '({},{},${})'.format(self.name, self.age, self.salary)


from operator import attrgetter

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Kevin', 30, 80000)
e3 = Employee('Rose', 25, 90000)

employees = [e1, e2, e3]

s_employees = sorted[employees, key = attrgetter('age')]

print(s_employees)

我正在通过youtube学习并复制此代码自己尝试,但无法复制结果,我使用Windows系统和Atom编写代码,观看的视频是使用MAC系统和sublime吗它会有所不同吗?

s_employees =已排序[employees,key = attrgetter(' age')]                                         ^ SyntaxError:语法无效 [完成0.141秒]

2 个答案:

答案 0 :(得分:1)

更改为s_employees = sorted(employees, key=attrgetter('age'))

答案 1 :(得分:0)

在花哨的public static string Cut = Convert.ToChar(29) + "V" + Convert.ToChar(65) + Convert.ToChar(0); 句法糖之前,让我们试试这个:

attrgetter

接下来,您可以将lambda调用替换为:

s_employees = sorted(employees, key = lambda employee: employee.age)

虽然,我也会重写你的from operator import attrgetter s_employees = sorted(employees, key = attrgetter('age')) 课程来使用/继承Employee

collections.namedtuple