5-12 3,168 views
首字母大写(map函数)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def change(str):
return {'a':'A','b':'B','c':'C','d':'D','e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L','m':'M','n':'N','o':'O','p':'P','r':'R','s':'S','t':'T','u':'U','v':'V','w':'W','x':'X','y':'Y','z':'Z'}[str]
def char(str):
for i in str:
return change(str[0])+str[1:]
arr1 = ['asdas','basd','zxczas']
print map(char,arr1)
#结果
['Asdas', 'Basd', 'Zxczas']
过滤奇偶数(filter函数
def is_odd(n):
return n % 2 == 1
arr = range(20)
print filter(is_odd,arr)
#结果
C:\Python27\python.exe G:/Python/script.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
删除空字符串(filter和strip函数)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def not_empty(s):
return s and s.strip()
print filter(not_empty,['A','B','','D','E','','','asdasd',''])
#结果
#C:\Python27\python.exe G:/Python/script.py
#['A', 'B', 'D', 'E', 'asdasd']
判断一个数是否是素数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def isPrime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
print isPrime(127)
排序
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def cmp_ignore_case(s1, s2):
if s1 < s2:
return -1
if s1 > s2:
return 1
return 0
print sorted([213,22,321,52,223,12],cmp_ignore_case)
冒泡排序
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def sort(nums):
for i in range(len(nums)-1,-1,-1):
for j in range(i):
if nums[j] > nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
return nums
arr = [123,25,23,123,66,2323,125,66,22,66]
print range(len(arr)-1,-1,-1)
print sort(arr)
#测试
C:\Python27\python.exe G:/Python/script.py
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[22, 23, 25, 66, 66, 66, 123, 123, 125, 2323]
类的定义 引用
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Studet(object):
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print ('%s:%s' % (self.name,self.score))
Studet('kou',100).print_score()
### 斐波那切数列
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Fib(object):
def __init__(self):
self.a,self.b = 0 , 1
def __iter__(self):
return self
def next(self):
self.a,self.b = self.b,self.a+self.b
if self.a > 10000:
raise StopIteration()
return self.a
for n in Fib():
print n
try 机制
try:
print 'try...'
r = 10 / 0
print 'result',r
except ZeroDivisionError,e:
print 'execpt:',e
finally:
print 'finally...'
print 'END'
#jieguo
C:\Python27\python.exe G:/Python/hello.py
try...
execpt: integer division or modulo by zero
finally...
END