python练习(一)
1. 实现1-100的所有的和
def qiuhe(x, y):
return x + y
he = 0
for i in xrange(1, 101):
he =qiuhe(he,i)
print (he)
2. 实现1-500所有奇数的和
def is_odd(x):
return x % 2 == 1
def qiuhe(x, y):
return x + y
he = 0
for i in filter(is_odd,xrange(1,501)):
print (i)
he = qiuhe(he, i)
print (he)
3.求1+ 2! + 3! + 4! + ……20!的和
def qiuhe(x, y):
return x + y
def jiecheng(n):
if(n<=1):
return 1
else:
return jiecheng(n-1)*n
he = 0
for i in xrange(1, 21):
he +=jiecheng(i)
print (he)
4.对指定一个list进行排序[2,32,43,453,54,6,576,5,7,6,8,78,7,89]
list.sort() 在本地进行排序,不返回副本
或者
def cmp_value(x,y):
if x > y :
return 1
elif x < y:
return -1
else:
return 0
listsorted=[2,32,43,453,54,6,576,5,7,6,8,78,7,89]
so=sorted(listsorted,cmp=cmp_value)
print (so)
5.字典排序,字符串, list, tuple常用方法
字典排序:
import operator
d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
print (sorted(d.iteritems(),key=operator.itemgetter(1)))
list:
classmates = ['Michael', 'Bob', 'Tracy']
#len
print (len(classmates))
#index
print (classmates[0])
#-1
print (classmates[-1])
#append
classmates.append('Adam')
print (classmates)
#insert
classmates.insert(1,'Jack')
print (classmates)
#pop
classmates.pop(1)
print (classmates)