首页 > 解决方案 > 如何编写一个函数来计算python中从n到m位置的列表中偶数元素的乘积?

问题描述

这是我已经尝试过的,但它只显示了两个值,我想查看该区间内的所有偶数值,这可能吗?

eL = [8, 2, 4, 5, 6, 10]
m = []
n = []

for x in eL:
    if x % 2 == 0 and x == eL[0]:
        m.append(x)

for x in eL:
    if x % 2 == 0 and x == eL[4]:
        n.append(x)

print(m, n)

例如,
对于列表[8, 2, 4, 5, 6,10]

结果 n = 1应该m = 3
2 · 4

对于n = 0m = 3
结果应该是8 · 2 · 4

而对于n = 2m = 4它应该是4 · 6

标签: pythonlist

解决方案


这是代码:

eL = [8, 2, 4, 5, 6, 10]
m = 1
n = 3
result = []
for x in eL:
    if x % 2 == 0 and (eL.index(x) >= m and eL.index(x) <= n):
        result.append(x)
print(result)

您可以使用.index>=, <=

或者(感谢Tal J. Levy的评论)

eL = [8, 2, 2, 4, 5, 6, 10]
m = 1
n = 3
result = []
for x in eL[m:n+1]:
    if x % 2 == 0:
        result.append(x)
print(result)

像这样循环它:for x in eL[m:n+1]:


推荐阅读