python - 如何编写一个函数来计算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 = 0
,m = 3
结果应该是8 · 2 · 4
而对于n = 2
,m = 4
它应该是4 · 6
。
解决方案
这是代码:
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]:
推荐阅读
- ruby-on-rails - Sprockets::Rails::Helper::AssetNotPrecompiled in Users#index
- c# - 使用 DataBound 显示重复项和禁用按钮
- java - 如何将mysql查询转换为JPQL
- azure - Azure 虚拟广域网负载平衡
- kubernetes - Pod 自我删除
- google-apps-script - 使用谷歌应用脚本创建一个充满图像的文档
- javascript - 如何在 package.json 中使用带有 npm 7.xx 的变量?
- java - java中String到arrayList的转换问题
- json - Pug.js 在每个循环中使用空格键或空格访问 json 键
- sql - 使用 SQL Server 选择除 ONE 之外的所有列