首页 > 解决方案 > 请帮我解决这个基本的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] 这显然是不正确的......

标签: pythonpython-3.xpython-2.7

解决方案


您需要检查内部的第 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?


推荐阅读