Python中将字符串列表转换为排序后的整数列表
使用Python分析数据时,我们可能会遇到将数字表示为字符串的情况。在本文中,我们将处理一个包含以字符串形式存在的数字的列表,我们需要将其转换为整数,然后以排序的方式表示它们。
使用map和sorted
在这种方法中,我们使用map函数将int函数应用于列表的每个元素。然后,我们将sorted函数应用于列表,该函数对数字进行排序。它也可以处理负数。
示例
listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Use mapp
listint = map(int, listA)
# Apply sort
res = sorted(listint)
# Result
print("Sorted list of integers: \n",res)输出
运行上述代码将得到以下结果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
使用int和sort
在这种方法中,我们使用for循环应用int函数并将结果存储到列表中。然后,将sort函数应用于列表。最终结果显示排序后的列表。
示例
listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = [int(x) for x in listA]
# Apply sort
res.sort()
# Result
print("Sorted list of integers: \n",res)输出
运行上述代码将得到以下结果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
使用sorted和int
这种方法与上述方法类似,只是我们将int函数通过for循环应用,并将结果包含在sorted函数中。这是一个单一表达式,它给我们最终的结果。
示例
listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = sorted(int(x) for x in listA)
# Result
print("Sorted list of integers: \n",res)输出
运行上述代码将得到以下结果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP