# 获取一个基于列表第一个元素进行乘法或求和的函数

2023-12-12 15:27:27

## 4 回答

TA贡献1821条经验 获得超4个赞

def simpleSum(mylist):

number = 1

for n in mylist:

if n % 2 != 0:

return sum(mylist)

else:

number *= n

return number

print(simpleSum([1, 2, 4, 5]))

print(simpleSum([2, 4, 5, 6]))

def simpleSum(mylist):

if mylist[0] % 2 != 0:

return sum(mylist)

else:

number = 1

for n in mylist:

number *= n

return number

print(simpleSum([1, 2, 4, 5]))

print(simpleSum([2, 4, 5, 6]))

HUX布斯

TA贡献1876条经验 获得超6个赞

• `number = 1`充当乘法的基值。

• `number *= n`等于`number = number * n`

def simpleSum(mylist):

if (mylist[0] % 2) == 0:

number = 1

for n in mylist:

number *= n

return number

else:

return sum(mylist)

print(simpleSum([1, 2, 4, 5]))

print(simpleSum([2, 4, 5, 6]))

TA贡献1830条经验 获得超9个赞

from functools import reduce

from operator import mul

def my_func(some_list):

return sum(some_list) if some_list[0] % 2 else reduce(mul, some_list)

print(my_func([1, 2, 4, 5]))

print(my_func([2, 4, 5, 6]))

12

240

TA贡献1828条经验 获得超3个赞

if my_list[0] % 2 == 0:

print(sum(my_list)

else:

num = 1

for n in my_list:

num *= n

print(num)

• 4 回答
• 0 关注
• 92 浏览

0/150