Python中的词表顺序
我们将介绍Python中的lexicographic order
。我们还将通过实例讨论实现词法排序的不同方法。
Python中的词法排序
在数学中,lexicographic
或lexicographical order
是对按字母顺序排列的元素列表或元素阵列进行排序的过程。用于lexicographic order
的另一个术语是dictionary order
。
词法排序有多种形式和概括,可以使用。简单地说,词法排序就是根据单词的首字母从列表或数组中进行排序。
如果首字母相同,则利用第二个字母来排序。我们可能会遇到一些情况,需要根据我们的要求对数据进行排序,这时我们会利用词法排序来对数据进行排序。
让我们结合实例讨论一下lexicographic order
,以便更好地理解它。如下所示,我们将创建一个包含一些随机事物名称的样本列表,我们将使用sort()
方法进行排序。
代码:
# python
sampleData = ["Egg", "Milkshake", "Banana", "Apple"]
print("List before using Lexicographical Order: ", sampleData)
sampleData.sort()
print("List after using Lexicographical Order: ", sampleData)
输出:
对上面的列表的排序是按字母顺序进行的。
在下一个例子中,我们将使用一个字符串而不是一个列表来应用lexicographic order
。我们将使用split()
函数将字符串转换为列表,然后使用sort()
函数。
代码:
# python
def LexicographicSort(sampleData):
Data = sampleData.split()
Data.sort()
for a in Data:
print ( a )
sampleData= "Let's try to sort this string into Lexicographical order"
print ("String before using Lexicographical Order: ", sampleData)
print ("String after using Lexicographical Order: ")
LexicographicSort(sampleData)
输出:
使用sort()
和split()
函数,我们可以将字符串排序到lexicographic order
。
在Python中把数字列表排序为词汇学顺序
我们也可以使用sort()
函数对数字列表进行排序。在这个例子中,我们将使用一个随机的数字数组,我们可以使用sort()
函数进行排序。
代码:
# python
def LexicographNumberSort(RangedNum):
RangedNum.sort()
print (RangedNum)
RangedNum = [1, 4, 5, 3, 10, 16, 12]
print ("Sorted numbers: ")
LexicographNumberSort(RangedNum)
输出:
sort()
方法可以将一个数字列表按词典顺序排序。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。