python中的小技巧

1.求1~100以内的素数

prime=filter(lambda x: not [x%i for i in range(2,x) if x%i==0], range(2,101))#列表推导,一行搞定.
print prime

2.求字符串子串

s=‘hauifnefldmfp‘
[s[i:i+n] for i in range(len(s)) for n in range(1, len(s)-i+1)]

3.求任意字符串中,所有符合ab 类型的子串:

  eg:s =‘aabbbb123456jjiidddccc‘

    结果:       

      aabb
      jjii
      iidd
      ddcc

def find_child(s):
    list = [s[i:i+n] for i in range(len(s)) for n in range(1, len(s)-i+1)]
    l=[]
    for z in s:
        if z not in l:l.append(z) 

    for k in range(1,len(l)):
        n, n2 = l[k-1], l[k]
        for i in range(len(l)/2):
            n, n2 = n+l[k-1], n2+l[k]
            result = n + n2
            final = [d for d in list if d == result]
            if final !=[]:print final[0]

if __name__ == ‘__main__‘:
    s =‘aabbbb123456jjiidddccc‘
    find_child(s)

  

  

python中的小技巧,布布扣,bubuko.com

python中的小技巧

上一篇:0712-----C++Primer听课笔记----------IO流


下一篇:Centos7 Snapper快照备份