标签:奇数 练习 字典 小结 items item reverse get type
1、实现1-100的所有的和
sum = 0 for i in range(101): sum +=i print(sum)
运行结果:
5050
2、实现1-500所有奇数的和
sum = 0 for i in range(1,501,2): sum +=i print(sum)
运行结果:
62500
3、求1+ 2! + 3! + 4! + ……20!的和
def myfact(n): if n < 0: print("负数没有阶乘!!!") elif n <2 : return 1 else : return n * myfact(n-1) def get_sum(m): sum = 0 for i in range(1,m+1): sum += myfact(i) return sum print(get_sum(20))
运行结果:
2561327494111820313
4、对指定一个list进行排序[2,32,43,453,54,6,576,5,7,6,8,78,7,89]
list1 = [2,32,43,453,54,6,576,5,7,6,8,78,7,89] print(type(list1)) list1.sort(reverse=False) print(list1) list2 = [2,32,43,453,54,6,576,5,7,6,8,78,7,89] list2.sort(reverse=True) print(list2) print(‘*‘*30)
运行结果:
<type ‘list‘>
[2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]
[576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]
5、字典排序
dic = {"d":87,"a":54,"c":15,"b":99,"e":66} #按字典键排序 a = sorted(dic.items(),key=lambda x:x[1],reverse=False) print(a) #按字典值排序 a = sorted(dic.items(),key=lambda x:x[0],reverse=False) print(a)
运行结果:
[(‘c‘, 15), (‘a‘, 54), (‘e‘, 66), (‘d‘, 87), (‘b‘, 99)]
[(‘a‘, 54), (‘b‘, 99), (‘c‘, 15), (‘d‘, 87), (‘e‘, 66)]
标签:奇数 练习 字典 小结 items item reverse get type
原文地址:http://www.cnblogs.com/pythonlx/p/7739742.html