首页 > 解决方案 > 修改列表 Python 的内容

问题描述

这是我遇到问题的 coursera Google 问题提示:

skip_elements 函数返回一个列表,该列表包含输入列表中的所有其他元素,从第一个元素开始。完成此功能,使用 for 循环遍历输入列表

原始代码:

def skip_elements(elements):
  # Initialize variables
  new_list = []
  i = 0

  # Iterate through the list
  for ___
      # Does this element belong in the resulting list?
      if ___
          # Add this element to the resulting list
          ___
      # Increment i
      ___

  return ___

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be 
['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

我有的:

def skip_elements(elements):
  # Initialize variables
  new_list = []
  i = 0

  # Iterate through the list
  for i in elements:
      # Does this element belong in the resulting list?
      if i % 2 == 0:
          # Add this element to the resulting list
          new_list.insert(i)
      # Increment i
      i += 1

  return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be 
['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

标签: pythonlist

解决方案


对您的代码进行最小的更改并且没有枚举:

def skip_elements(elements):
  # Initialize variables
  new_list = []
  i = 0

  # Iterate through the list by value and not index
  for elem in elements:
      # Does this element belong in the resulting list? Check on index
      if i % 2 == 0:
          # Add this element to the resulting list
          new_list.append(elem)
      # Increment index
      i += 1

  return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be 
['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

经典方式:

def skip_elements(elements):
  # Initialize variables
  new_list = []

  # Iterate through the list by index
  for i in range(len(elements)):
      # Does this element belong in the resulting list?
      if i % 2 == 0:
          # Add this element to the resulting list (value at index)
          new_list.append(elements[i])

  return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be 
['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

输出:

['a', 'c', 'e', 'g']
['Orange', 'Strawberry', 'Peach']
[]

因为我们喜欢它:单线

def skip_elements(elements):
  return [elements[i] for i in range(len(elements)) if i % 2 == 0 ]

推荐阅读