| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
就是最后面三行的排序 
我只看的懂一个reversed和sorted 
能帮我解释一下sorted括号里面的东西是什么意思吗 
越详细越好,麻烦各位了!感谢! 
 
 
a = input("请输入水果名称:").split(',') 
b = input('请输入水果价格:').split(',') 
 
c = [] 
for i in b: 
    c.append(int(i)) 
 
d= dict(zip(a,c)) 
print(d) 
 
e = input('请输入水果名字:') 
print(f'{e}的价格为:{d[e]}') 
 
d = reversed(sorted(d.items(),key= lambda x:x[1])) 
for i in d: 
    print(f'{i[0]}\t的价格:{i[1]}') 
 本帖最后由 阿奇_o 于 2021-5-21 21:30 编辑 
- In [3]: sorted?
 
 - Signature: sorted(iterable, /, *, key=None, reverse=False)
 
 - Docstring:
 
 - Return a new list containing all items from the iterable in ascending order.
 
 - A custom key function can be supplied to customize the sort order, and the
 
 - reverse flag can be set to request the result in descending order.
 
 - Type:      builtin_function_or_method
 
  
- In [5]: d = {'peach': 4, 'apple': 5, 'lychee': 10}
 
  
- In [6]: d
 
 - Out[6]: {'peach': 4, 'apple': 5, 'lychee': 10}
 
  
- In [7]: sorted(d.items())
 
 - Out[7]: [('apple', 5), ('lychee', 10), ('peach', 4)]  #sorted默认是按字典的key的字母升序排,在这里就是按水果的名称来排
 
  
- In [9]: sorted(d.items(), key=lambda item: item[1])  # 用参数key=..意思是 你可以指定按什么来排,这里即 比较 每个item的item[1]的大小,即按价格排(升序)。 
 
 - # 关于lambda匿名函数,简单理解就是:lambda 输入什么 : 输出什么
 
  
- Out[9]: [('peach', 4), ('apple', 5), ('lychee', 10)]
 
  
- In [10]: sorted(d.items(), key=lambda item: item[1], reverse=True)  # 按价格降序排
 
 - Out[10]: [('lychee', 10), ('apple', 5), ('peach', 4)]
 
  复制代码 
 
 
 |   
 
 
 
 |