Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sort在python中使用namedtuple编码_Python_Sorting_Namedtuple - Fatal编程技术网

使用sort在python中使用namedtuple编码

使用sort在python中使用namedtuple编码,python,sorting,namedtuple,Python,Sorting,Namedtuple,写一系列语句,按从最便宜到最贵的顺序打印出餐馆的列表。它应该使用sort和key=restaurant\u price作为参数进行排序 鉴于此代码: from collections import namedtuple Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price') RC = [ Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob",

写一系列语句,按从最便宜到最贵的顺序打印出餐馆的列表。它应该使用sort和key=restaurant\u price作为参数进行排序

鉴于此代码:

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()))
“我的代码”得到一个名为“sort”的错误语句未定义

sort是一个对原始列表进行操作且不返回任何值的就地方法,您可以使用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)]
或呼叫。在列表中排序:

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

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']

如果没有括号,它不是key=restaurant\u price吗?当我执行RC.sortkey=restaurant\u price然后打印RC时,我会收到一条错误消息:restaurant\u price缺少1个必需的位置参数:“restaurant'@anonymousfox,restaurant\u price上没有参数OK,但是我如何让它按照从最便宜的菜到最昂贵的菜的顺序只打印餐厅名称的列表,而不是该餐厅的所有属性的列表?如何在不使用for循环或if语句的情况下进行打印?