Python代码相关

如何反向迭代一个序列

法一:
list.reverse()
for i in list:

for i in range(len(list)-1,-1,-1):
 print(list[i])

如何查询和替换一个文本中的字符串

#最简单的方法使用replace()
tempstr = "hello you hello python are you ok"
print tempstr.replace("you","python")
#还可以使用正则,有个sub()
tempstr = "hello you hello python are you ok"
import re
rex = r'(hello|Use)'
print re.sub(rex,"Bye",tempstr)

?*使用python实现单例模式

重新实现str.strip()

在这里插入代码片

打乱一个排好序的列表

from random import shuffle
alist = [i for i in range(10)]
print(alist)
shuffle(alist)
print(alist)

?输入一个日期,返回时一年中的哪一天

利用datetime

from datetime import datetime
def which_day(year,month,day):
    return (datetime(year,month,day)-datetime(year,1,1)).days+1

print(which_day(2017,1,15))

?判断输入的值是否在矩阵之中(杨氏矩阵)

判断最大公约数和最小公倍数

def max_common(a,b):
    while b:
        a,b=b,a%b
    return a
def min_common(a,b):
    c= a*b
    while b:
        a,b=b,a%b
    return c//a

获取中位数

如果总数个数是奇数,按从小到大的顺序,取中间的那个数;如果总数个数是偶数个的话,按从小到大的顺序,取中间那两个数的平均数。

def mediannum(num):
    listnum = [num[i] for i in range(len(num))]
    listnum.sort()
    lnum = len(num)
    if lnum % 2 == 1:
        i = int((lnum - 1) // 2)
        return listnum[i]
    else:
        i = int(lnum // 2)
        return (listnum[i-1] + listnum[i ]) / 2

猜你喜欢

转载自blog.csdn.net/wenlyq/article/details/88821043