[英]How can I sort a string of characters in python?
I cannot find an answer elsewhere on this site, which is why I am asking.我在本网站的其他地方找不到答案,这就是我问的原因。 My answer is different as it contains alpha-numeric values and will not work with any integer based solution here is a sample of my string:我的答案是不同的,因为它包含字母数字值并且不适用于任何基于整数的解决方案,这里是我的字符串示例:
01768
01785
01799
01804
01818
01821
01835
01849
01852
01866
XXXXX
What can i do to sort these in ascending/descending order, so far i have tried sorted()
as it is used for stings, the output of this is ['0', '1', '6', '6', '8'] ['X', 'X', 'X', 'X', 'X']
.我能做些什么来按升序/降序对它们进行排序,到目前为止我已经尝试过sorted()
因为它用于刺痛,它的输出是['0', '1', '6', '6', '8'] ['X', 'X', 'X', 'X', 'X']
。 i want each separate value to be ordered and not individual characters.我希望对每个单独的值进行排序,而不是单个字符。 Any help is appreciated.任何帮助表示赞赏。
If you want to sort all these strings by their integer value then you can do this :如果要按整数值对所有这些字符串进行排序,则可以执行以下操作:
sorted(arr,key=lambda x:int(x))
Where arr
is the list of all those strings.其中arr
是所有这些字符串的列表。
Using sorted
使用sorted
Ex:前任:
s = """01768
01785
01799
01804
01818
01821
01835
01849
01852
01866"""
print("Ascending")
print( "\n".join(map(str, sorted(map(int, s.splitlines())))) )
print("---")
print("Descending")
print( "\n".join(map(str, sorted(map(int, s.splitlines()), reverse=True))) )
Output:输出:
Ascending
1768
1785
1799
1804
1818
1821
1835
1849
1852
1866
---
Descending
1866
1852
1849
1835
1821
1818
1804
1799
1785
1768
Using this answer as a guide Does Python have a built in function for string natural sort?使用此答案作为指南Python 是否具有用于字符串自然排序的内置函数?
alist = ['01768',
'01785',
'01799',
'01804',
'01818',
'01821',
'01835',
'01849',
'01852',
'01866',
'XXXXX']
from natsort import natsorted, ns
r = natsorted(alist, key=lambda y: y.lower())
>>>print(r)
['01768', '01785', '01799', '01804', '01818', '01821', '01835', '01849', '01852', '01866', 'XXXXX']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.