干货||20组常用的Python代码

1.for循环求和

sum = 0

for x in list(range(10)):

sum = sum + x

print(sum)

2.while循环

L = []

n = 1

while n <= 99:

L.append(n)

n = n + 2

print(L)

3.if条件判断

age = 20

if age >= 18:

print('your age is', age)

print('adult')

4.写入文件

with open('yourpath', 'w') as f:

f.write('Hello, world!')

5.列表生成式

with open('yourpath', 'w') as f:

f.write('Hello, world!')

6.列表切片

L = list(range(100))

print(L[:10])

7.正则表达

import re

m = re.search('(?<=abc)def', 'abcdef')

print(m.group(0))

8.Lamnda表达式

def make_incrementor(n):

return lambda x: x + n

if __name__ == "__main__":

f = make_incrementor(42)

print(f(0))

print(f(1))

9.快速排序

def quicksort(array):

if len(array) < 2:

return array

else:

pivot = array[0]

smaller = [i for i in array[1: ] if i <= pivot]

greater = [i for i in array[1: ] if i > pivot]

return quicksort(smaller) + [pivot] + quicksort(greater)

print(quicksort([5, 7, 3, 1, 9]))

10.变量交换

a = 1

b = 2

a, b = b, a

print(a, b)

11.@property装饰器

class Wage:

def __init__(self, wage=6000):

self.__wage = wage

@property

def wage(self):

return self.__wage

@wage.setter

def wage(self, value):

if isinstance(value, int):

self.__wage = value

else:

print("error: wage not int type!")

if __name__ == "__main__":

a = Wage(6800)

print(a.wage)

a.wage = 8000

print(a.wage)

12.closure闭包

def make_fact():

def fact(n):

if n == 1:

return 1

else:

return n * fact(n - 1)

return fact

fact = make_fact()

print(fact(7))

13.decorator装饰器

import time

def outer(func):

def inner(*args, **kwargs):

print("%s is called at %s" % (func.__name__, time.ctime()))

func(*args, **kwargs)

return inner

@outer

def f(a, b):

print("a + b = ", a + b)

f(1, 2)

14.urllib网络爬虫

import urllib.request

request = urllib.request.Request('http://www.python.org')

response = urllib.request.urlopen(request)

html = response.read(50).decode()

print(html, '\n')

print("response.getcode() = ", response.getcode(), '\n')

print("response.geturl() = ", response.geturl(), '\n')

print("response.info() = ", response.info())

15.fork多进程

import os

pid = os.fork()

if pid < 0:

print("fork failed!")

elif pid == 0:

print("我是子进程%s, 我的父进程是%s" % (os.getpid(), os.getppid()))

else:

print("我是父进程%s, 我的子进程是%s" % (os.getpid(), pid))

16.thread多线程

import threading

import time

def action(para):

time.sleep(1)

print('para == %s' % para)

for i in range(10):

t =threading.Thread(target=action,args=(i,))

t.start()

print('main thread end!')

17.运算符重载

class Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

def __str__(self):

return "({0}, {1})".format(self.x, self.y)

def __add__(self, other):

x = self.x + other.x

y = self.y + other.y

return Point(x, y)

if __name__ == "__main__":

p1 = Point(3, 5)

p2 = Point(2, -1)

print(p1 + p2)

18.斐波那契数列

def fib(n):

if n <= 2:

return 1

else:

return fib(n-1)+fib(n-2)

print(fib(7))

19.map( )函数

print(list(map((lambda x: x + 10),[1, 2, 3, 4])))

print(list(map(pow, [1, 2, 3], [2, 3, 4])))

print(list(filter((lambda x: x > 0), range(-5, 5))))

20.reduce()函数

import functools

print(functools.reduce((lambda x, y: x + y), [1, 2, 3, 4]))

print(functools.reduce((lambda x, y: x * y), [1, 2, 3, 4]))