python 字符串排序 偶数位交换_在Python中将字符串列表转换为整数排序列表

当我们必须处理以字符串表示的数字时,使用python分析数据可以为我们带来情景。在本文中,我们将获取一个列表,其中包含以字符串形式出现的数字,我们需要将其转换为整数,然后以排序方式表示它们。

带图和排序

在这种方法中,我们使用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函数并将结果存储到列表中。然后将排序功能应用于列表。最终结果显示排序列表。

示例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]

带排序和整型

此方法与上面的方法类似,除了我们通过for循环应用int函数并将结果封装在有序函数中。它是一个单一表达式,可为我们提供最终结果。

示例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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值