python练习笔记——map | sum | pow 的应用

时间:2021-07-20 20:21:32

1 函数简要

map 函数  | sum 函数  |  pow函数  | lambda函数

2 简要计算

2.1 1^2 + 2^2 + 3^2 .....9^2

方法1

print([pow(x,2) for x in range(1,10)])
#[1, 4, 9, 16, 25, 36, 49, 64, 81]
print(sum(pow(x,2) for x in range(1,10)))

方法2

print(map(pow,range(1,10),[2 for x in range(9)]))
# <map object at 0x7f9c0e4eb6a0>

print([i for i in map(pow,range(1,10),[2 for x in range(9)])])
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

print(sum(map(pow,range(1,10),[2 for x in range(9)])))

方法3

print(sum(map(lambda x : x ** 2,range(1,10))))

2.2  1^9 + 2^8 + 3^7 .....9^1

方法1

print(sum(map(pow,range(1,10),range(9,0,-1))))

肢解start

print([i for i in range(9,0,-1)])
# [9, 8, 7, 6, 5, 4, 3, 2, 1]
a = map(pow,range(1,10),range(9,0,-1))
print([i for i in a])
[1, 256, 2187, 4096, 3125, 1296, 343, 64, 9]

肢解end

方法2

print([pow(x,y) for x in range(1,10) for y in range(9,0,-1)])
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 512, 256, 128, 64, 32, 16, 8, 4, 2, 19683, 6561, 2187, 729, 243, 81, 27, 9, 3, 262144, 65536, 16384, 4096, 1024, 256, 64, 16, 4, 1953125, 390625, 78125, 15625, 3125, 625, 125, 25, 5, 10077696, 1679616, 279936, 46656, 7776, 1296, 216, 36, 6, 40353607, 5764801, 823543, 117649, 16807, 2401, 343, 49, 7, 134217728, 16777216, 2097152, 262144, 32768, 4096, 512, 64, 8, 387420489, 43046721, 4782969, 531441, 59049, 6561, 729, 81, 9]

print(sum([pow(x,y) for x in range(1,10) for y in range(9,0,-1)]))

上面的方法没有达到题目的要求,因为该段代码相对于将两个迭代参数全部遍历计算了一遍

改进为下列代码

print([pow(x,10-x) for x in range(1,10)])
# [1, 256, 2187, 4096, 3125, 1296, 343, 64, 9]

print(sum([pow(x,10-x) for x in range(1,10)]))

2.3 12 + 22 + 32 + 42....92

方法1

print([i*10+2 for i in range(1,10)])
# [12, 22, 32, 42, 52, 62, 72, 82, 92]

print(sum([i*10+2 for i in range(1,10)]))

方法2

print(sum(map(lambda x : x * 10 + 2,range(1,10))))