Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

Python: sorting string numbers not lexicographically

I have an array of string-numbers, like:

numbers = ['10', '8', '918', '101010']

When I use sorted(numbers), I get them sorted lexicographically, e.g. '8' > '17'.

How can I iterate over the strings sorted according to the number value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the built-in sorted() function with a key int to map each item in your list to an integer prior to comparison:

numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

Output

['8', '10', '918', '101010']

Using this method will output a list of strings as desired.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...