There are both numbers and strings in the Python list. How to sort and iterate the output?

Recently, when I was communicating with a boss, I came up with a question: How to sort and iterate the output in a Python list that contains both numbers and strings?

I haven't studied this before, so I thought it was a bit simple. The original plan was to sort directly through the sort() method that comes with the list and then directly iterate through the for loop. The idea is as follows:

list_a = [1, "b", "100", 9, 0]

for i in list_a.sort():
    print(i)

But after actual debugging, I found that this will report an error:

TypeError: '<' not supported between instances of 'str' and 'int'

The reason is that the sort() method does not support sorting elements of two different types, str and int, at the same time……

T.T

I thought about it later, and in order to achieve the goal,the basic idea is to convert it to the same type first, and then sort and iterate.

First go eat and drink a lot, and then an idea flashes, and the method comes - you can convert all the elements in the list into str type, and then do the operation. This uses some features in the sorted() method, and the final implementation is as follows:

list_a = [1, "b", "100", 9, 0]

print(sorted(list_a, key=str))
# 正序
for i in sorted(list_a, key=str):
    print(i, end=" ")
print()
# 逆序
for x in sorted(list_a, key=str, reverse=True):
    print(x, end=" ")

operation result:

[0, 1, '100', 9, 'b']
0 1 100 9 b
b 9 100 1 0

Attached:

The parameter key=... in the sorted() method has many other uses——

If the list is all strings, you can sort them according to the length of the strings. Here is a demo:

# 按照字符串长度排序
list_b = ["Bob", "Williams", "Kelly", "Eric", "Mary"]
for n in sorted(list_b, key=len):
    print(n, end=" ")

operation result:

Bob Eric Mary Kelly Williams

The key parameter can also accept expressions and some iterable functions. Friends who are interested in the specific gameplay can study it. I wish everyone will become a boss as soon as possible~~~

Guess you like

Origin blog.csdn.net/m0_54701273/article/details/129078370