Python实现字符的冒泡排序——说实话,两个数兑换的方法震惊了我,一天比一天感受到了Python的强大

import  random
M=10
lettList=[]
for i in range(M):
    lettList.append(chr(random.randrange(65,90)))
for lett in lettList:
    print("{}:{}".format(lettList.index(lett),lett))
# 冒泡排序

for i in range(M-1):
    for j in range(M - 1-i):
        if lettList[j] > lettList[j + 1]:
            lettList[j] , lettList[j + 1]=lettList[j + 1],lettList[j]
print("遍历后;",lettList)

这是对随机产生的A~Z的字符进行排序,适合图书馆书籍的排序实例!

啊还是太年轻,我又学到了Python中的一些方法,原来人家对数字的数据本来就有函数,而且正序,逆序,插入,删除,应有尽有,请看下例:

import  random
numList=[]
M=10
for i in range(M):
    numList.append(random.randrange(1,50))
print("未排序的数组:",numList)

numList.sort()
print("排序后的数组:",numList)

# 逆序排序有两种方式
numList.sort(reverse=True)
print("逆序排序后的数组:",numList)

numList.reverse()
print("逆序排序后的数组:",numList)

# 插入数据
numList.insert(2,10)
print(numList)

# 删除数据
numList.remove(10)
print(numList)

# 删除索引上的数据
numList.pop(0)
print(numList)

numList[0]=99
# sorted内置函数,不会真正对原列表,只会输出时排序的
print(sorted(numList))
print(numList)

输出结果:

未排序的数组: [4, 27, 20, 38, 8, 21, 22, 35, 43, 14]
排序后的数组: [4, 8, 14, 20, 21, 22, 27, 35, 38, 43]
逆序排序后的数组1: [43, 38, 35, 27, 22, 21, 20, 14, 8, 4]
逆序排序后的数组1: [4, 8, 14, 20, 21, 22, 27, 35, 38, 43]
插入数据后列表 [4, 8, 10, 14, 20, 21, 22, 27, 35, 38, 43]
删除数据后列表 [4, 8, 14, 20, 21, 22, 27, 35, 38, 43]
按索引删除数据后列表 [8, 14, 20, 21, 22, 27, 35, 38, 43]
sorted内置函数,不会真正对原列表: [14, 20, 21, 22, 27, 35, 38, 43, 99]
sorted内置函数排序后,原来的列表 [99, 14, 20, 21, 22, 27, 35, 38, 43]

 

posted @ 2019-05-23 20:57  木&子  阅读(333)  评论(0编辑  收藏  举报