Python程序中按任意键对元组进行升序排序
在本教程中,我们将学习如何按第n个索引键对元组列表进行升序排序。例如,我们有一个元组列表**[(2, 2), (1, 2), (3, 1)]**,我们需要使用第0个索引元素对其进行排序。该列表的输出将是**[(1, 2), (2, 2), (3, 1)]**。
我们可以使用**sorted**方法实现这一点。在将列表传递给**sorted**函数时,我们必须传递一个**key**。这里,key是排序所基于的索引。
**sorted**接受一个列表,并返回按升序排列的列表。如果要按降序排列列表,则在**sorted**函数中将**reverse**关键字参数设置为**True**。
让我们看看解决问题的步骤。
算法
1. Initialize list of tuples and key 2. Define a function. 2.1. Return key-th index number. 3. Pass list of tuples and function to the sorted function. We have to pass function name to the keyword argument key. Every time one element (here tuple) to the function. The function returns key-th index number. 4. Print the result.
示例
## list of tuples tuples = [(2, 2), (1, 2), (3, 1)] ## key key = 0 ## function which returns the key-th index number from the tuple def k_th_index(one_tuple): return one_tuple[key] ## calling the sorted function ## pass the list of tuples as first argument ## give the function as a keyword argument to the **key** sorted(tuples, key = k_th_index)
输出
如果运行上面的程序,您将得到以下结果。
[(1, 2), (2, 2), (3, 1)]
如果将key初始化为大于len(tuple) - 1的索引,则会得到索引错误。让我们来看看。
示例
## list of tuples tuples = [(2, 2), (1, 2), (3, 1)] ## key ## initializing the key which is greter than len(tuple) - 1 key = 2 ## function which returns the key-th index number from the tuple def k_th_index(one_tuple): return one_tuple[key] ## calling the sorted function ## pass the list of tuples as first argument ## give the function as a keyword argument to the **key** sorted(tuples, key = k_th_index)
输出
如果运行上面的程序,您将得到以下结果。
IndexError Traceback (most recent call last) <ipython-input-13-4c3fa14880dd> in <module> 13 ## pass the list of tuples as first argument 14 ## give the function as a keyword argument to the **key** ---> 15 sorted(tuples, key = k_th_index) <ipython-input-13-4c3fa14880dd> in k_th_index(one_tuple) 8 ## function which returns the key-th index number from the tuple 9 def k_th_index(one_tuple): ---> 10 return one_tuple[key] 11 12 ## calling the sorted function IndexError: tuple index out of range
上面的程序适用于任意数量的元组和任意大小的元组,除非索引不超过**len(tuple) - 1**。
结论
希望您喜欢本教程。如果您对本教程有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP