列表序列中的每个数值元素进行平方运算
r=map(lambda x:x**2,[1,2,3,4])
print(list(r))
1,4,9,16
其中运用到了map函数和lambda函数
map()
函数接收两个参数,一个是function
函数,另一个参数是一个或多个序列
对map()
函数传入的两个序列中的元素依次求和
r=map(lambda x,y:x+y,[1,2,3],[4,5,6])
print(list(r))
[5,7,9]
由此可见,function
函数的参数数量,应和map()
函数传入的序列数量相匹配。
reduce函数
from functools import reduce
r=reduce(lambda x,y:x+y,[1,2,3,4,5],6)
print(r)
6+1+2+3+4+5=21
# coding=utf-8
from functools import reduce
# 输入一个正整数
x = int(input())
# 定义factors函数,返回x的分解质因数,例如factors(80)返回[2,2,2,2,5]
def factors(x):
t = x
i = 2
L=[]
while t>1:
if t%i==0:
L.append(i)
t = t/i
else:
i+=1
return L
L=factors(x) #例如x为80时L为[2,2,2,2,5]
########## Begin ##########
#(1) 输出结果,利用map()函数将L的值按照字符串格式输出('*'.join(方法))
print('{} = {}'.format(x, '*'.join(map(str, L))))
# (2)输出L中所有值累积的结果
accumulated_result = reduce(lambda a, b: a * b, L,1)
print(accumulated_result)
########## End ##########
拆分一下
- 定义质因数分解函数:
def factors(x): i = 2 prime_factors = [] while i * i <= x: if x % i: i += 1 else: x //= i prime_factors.append(i) if x > 1: prime_factors.append(x) return prime_factors
factors
函数用于找出一个整数x
的所有质因数,并以列表的形式返回它们。它从2开始,检查x
是否能被i
整除。如果能,就将i
添加到质因数列表中,并将x
更新为x // i
(整除)。如果x
不能被i
整除,就增加i
的值。当i
的平方大于x
时,循环结束。如果x
此时仍然大于1,说明x
本身是一个质数,将其添加到质因数列表中。 -
print('{} = {}'.format(x, '*'.join(map(str, L))))
首先使用
map(str, L)
将L
中的每个整数元素转换为字符串,然后使用'*'.join()
将这些字符串以*
为分隔符连接成一个单一的字符串。最后,使用format
方法将x
和连接后的字符串格式化输出,形式为123456 = 2*2*2*2*2*2*3*643
。 -
map(str,L)
-
如果
L
是一个包含数字的列表,如[1, 2, 3]
,那么map(str, L)
将返回一个迭代器,其中包含['1', '2', '3']
-
str
是 Python 内置的类型转换函数,它将传入的对象转换成字符串类型。map
函数接受两个参数:一个是函数(这里是str
),另一个是可迭代对象(这里是列表L)
-
4. '*'.join() 连接
将它们以 *
为分隔符合并成一个单一的字符串,用于输出质因数分解的可读格式
括号里可以是元组,列表(可迭代)
5. '{} = {}'.format() 字符串格式化方法,可以将变量嵌入到字符串中
花括号内的数字,0和1,可以省略不写,默认按顺序对应
product_of_prime_factors = reduce(lambda a, b: a * b, L, 1)
print("Product of prime factors:", product_of_prime_factors)