请帮我解决这个基本的python程序

时间:2020-03-28 11:00:01

标签: python python-3.x python-2.7

## 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],显然不正确...

1 个答案:

答案 0 :(得分:1)

您需要检查l内的 i-th 元素,而不是索引号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?