使用sort对带有namedTuple的python进行编码

时间:2015-01-21 22:42:32

标签: python sorting namedtuple

编写一系列语句,按照从最便宜到最贵(最好的菜)的顺序打印出餐馆RC列表。它应该使用sort()和key = restaurant_price作为sort()

的参数

鉴于此代码:

from collections import namedtuple 
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
RC = [
    Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50),
    Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50),
    Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50)]

def restaurant_price (restaurant:Restaurant)-> float:
    return restaurant.price

我写道:

print(sort(RC,key=restaurant_price()))

我的代码收到错误声明" name' sort'未定义"

1 个答案:

答案 0 :(得分:4)

sort是一个在原始列表上运行并返回None的inplace方法,可以使用sorted:

print(sorted(RC,key=restaurant_price)) # creates new list

使用已排序:

In [23]: sorted(RC,key=restaurant_price)
Out[23]: 
[Restaurant(name='Nobu', cuisine='Japanese', phone='335-4433', dish='Natto Temaki', price=5.5),
 Restaurant(name='Thai Dishes', cuisine='Thai', phone='334-4433', dish='Mee Krob', price=12.5),
 Restaurant(name='Nonna', cuisine='Italian', phone='355-4433', dish='Stracotto', price=25.5)]

或者在名单上拨打.sort:

RC.sort(key=restaurant_price) # sort original list 
print(RC) 

的.sort:

In [20]: RC.sort(key=restaurant_price)

In [21]: RC
Out[21]: 
[Restaurant(name='Nobu', cuisine='Japanese', phone='335-4433', dish='Natto Temaki', price=5.5),
 Restaurant(name='Thai Dishes', cuisine='Thai', phone='334-4433', dish='Mee Krob', price=12.5),
 Restaurant(name='Nonna', cuisine='Italian', phone='355-4433', dish='Stracotto', price=25.5)]

获取名称:

In [24]: [x.name for x in sorted(RC,key=restaurant_price)]
Out[24]: ['Nobu', 'Thai Dishes', 'Nonna']

不使用显式的for循环或zip:

from operator import itemgetter
print(list(map(itemgetter(0),sorted(RC,key=restaurant_price)))
['Nobu', 'Thai Dishes', 'Nonna']