python杂记
python实现switch语句
{
'0' : labmda : print('你是男的还是女的'),
'1' : labmda : print('你是男的'),
'2' : labmda : print('你是女的'),
}.get('1')()
python实现三目运算
#example1
(labmda x,y: x < y and x or y)(1,3)
#example2
(labmda x,y: x if x < y else y)(2,4)
python中exec和eval的用法
#example exec
exec("mult = lambda x,y: x**y")
print(mult(2, 3))
#example eval
print(eval("lambda x,y: x**y")(2,3))
python中enumerate带索引的遍历
str = 'mystring'
#lst = ['hello',',','type','.','so']
for idx , ele in enumerate(str):
print(idx,ele)
python中for else语句
import math
for i in range(100):
for t in range(2, int(math.sqrt(i)) + 1):
if i % t == 0:
break
else:
print(i)
python动态导入模块
mymod=__import__('mypackage', fromlist=["*"])
mymod.mydef()
python按行读取文件
#sample 基本的方法
file = open("sample.txt")
while True:
line = file.readline()
if not line:
break
pass
#sample 更快的方法
file = open("sample.txt")
while True:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass
python html中编码的汉字
抓取网页的时候可能会遇到(小子)这样的格式输出的汉字,我们想办法将他还原为真正的汉字
#10进制的
print(unichr(int('23567', 10)))
print(unichr(int('23376', 10)))
#16进制的
print(unichr(int('0x5c0f', 16)))
print(unichr(int('5b50', 16)))
#用HTMLParser模块
import HTMLParser
html_parser = HTMLParser.HTMLParser()
s = html_parser.unescape('小子')
print(s)
获取本机IP
import socket
print(socket.getaddrinfo(socket.gethostname(),None)[-1][4][0])
python中list相减
python中两个list可以相加,却不能相减,是不是很纠结。
list1 = [1, 2, 3, 4, 5]
list2 = [1, 3, 5]
#example1 转换为集合相减
list3 = list(set(list1) - set(list2))
#example2
list3 = [i for i in list1 if i not in list2]
判断list1是否为list2的子集
list1 = [1,3,5]
list2 = [1,3,5,7]
if all(x in list2 for x in list1):
print('子集')
读取大文件的指定行
def getline(thefilepath, desired_line_number):
if desired_line_number < 1: return ''
for current_line_number, line in enumerate(open(thefilepath, 'rU')):
if current_line_number == desired_line_number-1: return line
return ''
print写文件
f = open('out.txt','w+')
print >> f, 'hello', 'world'
f.close()
元祖传递函数参数
def add(a, b):
print a + b
opnds = (1,2)
add(*opnds)
单词首字母大写
string.capwords
string.capwords
一直觉得python很奇葩!
[code lang=python]print('Hello world.')[/code]
Hello world.