跳到主要内容

Python小技巧01

python中sorted函数是默认从小到大排序的

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 默认升序排序
ascending_sorted_numbers = sorted(numbers)

# 指定降序排序
descending_sorted_numbers = sorted(numbers, reverse=True)

print("Ascending:", ascending_sorted_numbers)
print("Descending:", descending_sorted_numbers)

sorted函数可以对字母的ascii码进行排序

从小到大

# 从小到大
s = "abcHelloWorld"
sorted_s = ''.join(sorted(s))

print(sorted_s)

从大到小

# 从大到小
s = "abcHelloWorld"
sorted_s = ''.join(sorted(s, reverse=True))

print(sorted_s)

比较两个列表是否相同可以直接使用'=='

list1 = [3, 2, 1]
list2 = [1, 2, 3]

if sorted(list1) == sorted(list2):
print("The lists contain the same elements.")
else:
print("The lists do not contain the same elements.")

from collections import Counter

list1 = [1, 2, 2, 3, 3, 3]
list2 = [3, 3, 3, 2, 2, 1, 2]

if Counter(list1) == Counter(list2):
print("The lists have the same elements and the same number of each element.")
else:
print("The lists do not have the same elements and/or counts.")

打印字母的ASCII码

# 使用内置函数ord函数
print(ord("a"))