冒泡排序

lis = [56,12,1,8,354,10,100,34,56,7,23,456,234,-58]
def sortport():
    for i in range(len(lis)-1):
        for j in range(len(lis)-1-i):
            if lis[j] > lis[j+1]:
                lis[j],lis[j+1] = lis[j+1],lis[j]
    return lis

计算x的n次方的方法

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

计算aa + bb + c*c + ……

def calc(numbers):
  sum = 0
  for n in numbers:
    sum = sum + n * n
  return sum

计算阶乘 n!

def factorial(n):
  result = n
  for i in range(1, n):
    result *= i
  return result

列出当前目录下的所有文件和目录名

print([d for d in os.listdir('.')])

把一个list中所有的字符串变成小写

L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])

输出某个路径下的所有文件和文件夹的路径

def print_dir():
  filepath = input("请输入一个路径:")
  if filepath == "":
    print("请输入正确的路径")
  else:
    for i in os.listdir(filepath):       #获取目录中的文件及子目录列表
      print(os.path.join(filepath,i))  #把路径组合起来

print(print_dir())

输出某个路径及其子目录下的所有文件路径

def show_dir(filepath):
  for i in os.listdir(filepath):
    path = (os.path.join(filepath, i))
    print(path)
    if os.path.isdir(path):      #isdir()判断是否是目录
      show_dir(path)             #如果是目录,使用递归方法

filepath = "C:\Program Files\Internet Explorer"
show_dir(filepath)

输出某个路径及其子目录下所有以.html为后缀的文件

def print_dir(filepath):
  for i in os.listdir(filepath):
    path = os.path.join(filepath, i)
    if os.path.isdir(path):
      print_dir(path)
    if path.endswith(".html"):
      print(path)

filepath = "E:\PycharmProjects"
print_dir(filepath)

把原字典的键值对颠倒并生产新的字典

dict1 = {'A':'a', 'B':'b', 'C':'c'}
dict2 = {y:x for x,y in dict1.items()}

打印九九乘法表

for i in range(1, 10):
    for j in range(1, i+1):
        # print('{}x{}={}\t'.format(j, i, i*j), end='')
        print('%d x %d = %d \t'%(i, j, i*j), end='')
    print()

替换列表中所有的3为3a

num = ["harden","lampard",3,34,45,56,76,87,78,45,3,3,3,87686,98,76]

for i in range(num.count(3)):
    ele_index = num.index(3)
    num[ele_index]="3a"
    print(num)

合并去重

list1 = [2, 3, 8, 4, 9, 5, 6]
list2 = [5, 6, 10, 17, 11, 2]

list3 = list1 + list2
print(list3)
print(set(list3))
print(list(set(list3)))

随机生成验证码的两种方式

第一种

import random
list1=[]
for i in range(65,91):
    list1.append(chr(i))
for j in range(97,123):
    list1.append(chr(j))
for k in range(48,58):
    list1.append(chr(k))
ma = random.sample(list1,6)
print(ma)
ma = ''.join(ma)
print(ma)

第二种

import random,string
str1 = "0123456789"
str2 = string.ascii_letters
str3 = str1+str2
ma1 = random.sample(str3,6)
ma1 = ''.join(ma1)
print(ma1)
最后修改:2020 年 07 月 30 日 10 : 41 AM