python - 请帮我解决这个基本的python程序
问题描述
## Example - Find the indices in a list where the item is a multiple of 7
def multiple_7(l):
indices_7 = []
for i in range(len(l)):
if(i%7 == 0):
indices_7 += [i]
return indices_7 ## list of all indices where the item is a multiple of 7
l = [2, 3, 7, 4, 14, 9] ## multiple_7 should return [2, 4]
print(multiple_7(l))
我得到输出 [0] 这显然是不正确的......
解决方案
您需要检查内部的第 i 个元素l
而不是索引号i
本身:
def multiple_7(l):
indices_7 = []
for i in range(len(l)):
if l[i] % 7 == 0: # <---fixed here
indices_7.append(i)
return indices_7 ## list of all indices where the item is a multiple of 7
l = [2, 3, 7, 4, 14, 9]
print(multiple_7(l))
输出:
[2,4]
您还可以将代码缩短为:
def multiple_7(l):
return [i for i,v in enumerate(l) if v%7==0]
任何时候您需要列表中某些内容的索引(和值)时,请使用enumerate
在此处阅读有关条件列表推导的更多信息:if/else in a list comprehension?
推荐阅读
- maven - 来自私人仓库的 Maven 扩展
- kotlin - 如何将 MutableList 添加到另一个 MutableList - Kotlin?
- regex - 有什么方法可以使用 RegEx 从磁力链接或 Flutter / Dart 中的复杂字符串中获取大小信息(MB,GB)?
- python - 我试图让用户在完成后一次又一次地重复while循环
- parallel-processing - F# Array.Parallel.map 不提供并行处理
- arrays - Go中protobuf数组元素的范围
- c++ - 我可以检查是否有任何数据发送到我的服务器而无需等待
- javascript - 如何管理用于在 ReactJS 中显示的 json 属性数组
- google-chrome - 将根证书添加到铬捆绑包
- c# - 在 C# 中更改变量值时记录类 Var 状态