for l1 in all1:
for l2 in all2:
if l1.strip()==l2.strip(): #比较行中内容是否一样
f3.write(l2)
else:
continue
else:
pass
print "#"*40
f3.close()
【例003】反向读取文件
假如要读取的test.txt文件内容如下:
复制代码 代码如下:
Python
Perl
Java
Shell
实现代码:
复制代码 代码如下:
file1 = file('test.txt','r')
list1 = [] #用一个空列表用于存放每行的内容
while True:
line = file1.readline()
list1.append(line.strip())
if len(line) == 0:
break
for l in list1[::-1]: #反向遍历,然后依次读取出来
print l
while True:
i += 1
line = f_r.readline()
if not line:
break
f_w.write('%02d'%(i) + '.Python 3.0: #' + line)#字符串格式化及拼接技巧
f_r.close() #关闭打开的文件句柄
f_w.close()
【例005】
复制代码 代码如下:
#coding = gbk
'''''
下面code.txt文件中内容,将
01 CN Chinese
02 IN India
03 HK HongKang
04 JP Japan
05 DE Germany
06 US United States of America
要文件的内容,每一行文件,写到一个文件,且文件名前面两个字段,如
文件名为:01_CN_Chinese.txt
文中内容:01 CN Chinese
知识要点:
1. ''.join 和 split函数
2. 字符的联合
3. with语句,open文件
4. 遍历数组
5. 切片操作
'''
postfix = '.txt' #设置后缀
with open('test.txt') as myfile: #with语句打开文件为myfile
while True: #while循环拿文件读出来
lines = myfile.readlines() #拿所有的行一次性读取到列表中
if not lines: break #没有则中断
for line in lines: #遍历列表
file_out = str('_'.join(line.split()[:])) + postfix #得到01_CN_Chinese.txt文件名
open(file_out,'w').write(line) #write(line),将没行的文件写入新文件中
def factorial(n):
return reduce(lambda x,y: x* y, range(1,n+1))#求6!
print reduce(lambda x,y: x + y, [factorial(i) for i in range(1,6)]) #求6! + 5! + 4! + 3! + 2! + 1!
【例008】 根据输入打印文件
复制代码 代码如下:
import sys
helpinfo= '''''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--[version|VERSION|V|v]: Prints the version number
--[help |HELP |H|h]: Display the help
'''
def readfile(filename):
try:
f = open(filename)
while True:
line = f.readline()
if not line:
break
print line,
except:
print 'some error here'
if len(sys.argv) < 2:
print 'No action is needed!'
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
if option in ['version','v','V','VERSION']:
print 'Version 1.0'
elif option in ['h','H','help','HELP']:
print helpinfo
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
【例009】函数中args的用法
复制代码 代码如下:
def powersum(power,*args):
'''''Print each argument's power'''
total = 0
for item in args:
total += pow(item,power)
return total
if os.system(zip_command) == 0:
print 'Scuccessful backup to', target
else:
print 'The backup FAILED'
输出结果 :
复制代码 代码如下:
# python backup_ver4.py
Enter comments here-->add new example
The backup directory created! /home/test/python20141202
Scuccessful backup to /home/test/python20141202/145130_add_new_example.zip
【例012】将二进制数转为10进制数
复制代码 代码如下:
def func(B):
I = 0
while B:
I = I * 2 + (ord(B[0])-ord('0'))
B = B[1:]
return I
b = raw_input('Enter binary here:')
print func(b)
【例013】将列表中排除重复项并将重复的项找出
复制代码 代码如下:
def find_duplicate(lst):
tmp = [] #临时变量,存放排除后的列表
for item in lst:
if not item in tmp: #将不在tmp变量找出
tmp.append(item)
else:
print 'The duplicate item is:', item
print 'After remove the duplicate item:',
return tmp
if __name__=='__main__':
test = input("Enter List here:") #input技巧
print find_duplicate(test)
>>>
Enter List here:[2,1,4,2]
The duplicate item is: 2
After remove the duplicate item: [2, 1, 4]
【例014】用Python中列表中append(),pop()函数实现简单的堆栈方法:后进先出
复制代码 代码如下:
l = []
l.append(1)
l.append(2)
l.append(3)
print l
print l.pop()
print l.pop()
print l.pop()
【例015】对列表中的单词按首字母排序
复制代码 代码如下:
>>> words = ['apple','bat','bar','book','atom']
>>> tmp = {} #建个空字典
>>> for word in words:
letter = word[0] #作为字典中的键
if letter not in tmp: #判断首字母是否存在于字典
tmp[letter] = [word] #注意要添加[],很关键
else:
tmp[letter].append(word) #如果键已经存在,值列表添加
john black
Jerry!
&alice
TOm#
south carolina###
mr smith?
代码及输出结果如下:
复制代码 代码如下:
import re
def clean(strings):
result = []
for value in strings:
value = value.strip()
value = re.sub('[#!&?]','',value)
value = value.title()
result.append(value)
return result
with open('data.txt','a+') as myfile:
lines = myfile.readlines()
for line in clean(lines):
print line
>>>
John Black
Jerry
Alice
Tom
South Carolina
Mr Smith
【例017】用while循环来判断某个数是否是质数
复制代码 代码如下:
y = input('Enter a integer Here:')
x = y / 2
while x > 1:
if y % x == 0:
print y, 'has factor', x
break
x -= 1
def list_remove(seq):
res = []
for i in seq:
if i not in res:
res.append(i)
return res
L1 = [3,1,2,3,8]
print list_remove(L1)
def find_duplicate(seq):
res = []
for i in range(len(seq)):
if seq.count(seq[i]) >= 2:
print 'Found %s'% seq[i], 'The index is:', i
res.append(seq[i])
return res
L1 = [3,1,2,3,8]
print find_duplicate(L1)
结果如下:
复制代码 代码如下:
>>>
[L1 - L2]: [1, 2]
[L1 & L2]: [3, 4]
[L1 | L2]: [1, 2, 3, 4, 5, 6]
[L1 ^ L2]: [1, 2, 5, 6]
[3, 1, 2, 8]
Found 3 The index is: 0
Found 3 The index is: 3
[3, 3]
def test():
print var
local();glob1();glob2();glob3()
print var
【例026】求range(10)中每个元素的立方
复制代码 代码如下:
def func():
res = []
for i in range(10):
res.append(lambda x, i=i: i ** x) #i=i这是关键,否则i默认记忆最后一个值:9
return res
>>> res = func()
>>> for i in range(10):
res[i](3)
0
1
8
27
64
125
216
343
512
729
【例027】求最小值
复制代码 代码如下:
def min1(*args):
mini = args[0]
for arg in args[1:]:
if arg < mini:
mini = arg
return mini
def min2(first,*rest):
mini = first
for arg in rest:
if arg < first:
mini = arg
return mini
def min3(*args):
res = list(args)
res.sort()
return res[0]
print min1('c','a','b')
print min2(3,1,4)
print min3(1,'a',78,'c')
def func(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y
def morethan(x, y): return x > y
def intersect(*args):
res = []
for x in args[0]:
for other in args[1:]:
if x not in other:
break
else:
res.append(x)
return set(res) #去除重复的部分
print intersect('SPAM','SCAM','SLAM')
def union(*args):
res = []
for seq in args:
for item in seq:
if not item in res:
res.append(item)
return res
print union('SA','SB','SC')
def intersect(*args):
res = []
for x in args[0]:
for other in args[1:]:
if x not in other:
break
else:
res.append(x)
#为了交互['S','S','A','A','M','M']
tmp = []
[tmp.append(i) for i in res if i not in tmp]
return tmp
print intersect('SCAM','SPAM','SLAM')
【例029】字典的拷贝及添加
复制代码 代码如下:
def copyDict(old):
new = {}
for key in old:
new[key] = old[key]
return new
def addDict(d1,d2):
new = {}
for key in d1.keys():
new[key] = d1[key]
for key in d2:
new[key] = d2[key]
return new
【例030】求质数
复制代码 代码如下:
def isPrime(y):
if y < 1:
print y, 'not prime'
else:
x = y // 2
while x>1:
if y % x == 0:
print y, 'has factor', x
break
x -= 1
else:
print y, 'is prime!'
【例031】比较多个值的大小
复制代码 代码如下:
def min_max(func,*args):
res = args[0]
for arg in args[1:]:
if func(arg,res):
res = arg
return res
def min_func(x,y): return x < y
def max_func(x,y): return x > y
if __name__=='__main__':
print "The min value is:", min_max(min_func,4,3,2,1,7,6,9)
print "The max value is:", min_max(max_func,4,3,2,1,7,6,9)
# 输出结果:
>>>
The min value is: 1
The max value is: 9
name = raw_input('Name: ')
#查找电话号码还是地址?
request = raw_input('Phone number (p) or address (a)? ')
#查找正确的键
key = request #如果请求即不是p也不是a
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
#使用get()函数提供默认值
person = peoples.get(name,{})
label = labels.get(key, key)
result = person.get(key, 'not available')
print "%s's %s is %s." % (name, label, result)
【例041】字典格式化字符串例子
复制代码 代码如下:
template='''''
%(title)s
%(text)s
'''
data = {'title':'My Home Page','text':'Welcome to my home page!'}
print template % data
#输出结果:
>>>
My Home Page
Welcome to my home page!
【例042】需找100以内的最大平方数
复制代码 代码如下:
from math import sqrt
#从100开始往下找,找到即停止,最大为: 81
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
【例043】用while/True, break控制输入
复制代码 代码如下:
while True: #一直进行下去,除非break
word = raw_input('Please Enter a word: ')
if not word: break #输入为空的话,中断循环
print 'The word was: ' + word
【例044】将两个列表中首字母相同的提取出来
复制代码 代码如下:
#将两个列表中首字母相同的罗列在一起
girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
#列表推导:
print [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
#输出结果:
>>>
['chris+clarice', 'arnold+alice', 'bob+bernice']
【例045】斐波那契数列求指定数字的列表
复制代码 代码如下:
def fibs(x):
fibs = [0, 1] # 初始值
for i in range(x):
# fibs[-2]+fibs[-1]:最新一个值是前面两个值之和
# 并用append方法将其添加在后面
fibs.append(fibs[-2]+fibs[-1])
print fibs
if __name__=='__main__':
num = input('How many Fibonacci numbers do you want? ')
fibs(num)
或者用普通方法实现:
复制代码 代码如下:
>>> def fib(max):
n, a, b = 0, 0, 1
tmp_list = []
while n < max:
tmp_list.append(a)
a, b = b, a+b
n += 1
return tmp_list
>>> fib(8)
[0, 1, 1, 2, 3, 5, 8, 13]
【例046】写一个自定义列表类,让它支持尽可能多的支持操作符号
复制代码 代码如下:
class MyList:
def __init__(self, start):
self.wrapped = [] # Make sure it's a list here
for x in start:
self.wrapped.append(x)
def __add__(self, other):
return MyList(self.wrapped + other)
def __mul__(self, time):
return MyList(self.wrapped * time)
def __getitem__(self, offset):
return self.wrapped[offset]
def __len__(self):
return len(self.wrapped)
def __getslice__(self, low, high):
return MyList(self.wrapped[low:high])
def append(self, node):
self.wrapped.append(node)
def __getattr__(self, name): # Other members: sort/reverse/etc
return getattr(self.wrapped, name)
def __repr__(self):
return repr(self.wrapped)
if __name__ == '__main__':
x = MyList('spam')
print x
print x