python - 修改列表 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 []
解决方案
对您的代码进行最小的更改并且没有枚举:
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 ]
推荐阅读
- sql - 我需要 JSON 数组中的所有值
- modelica - 在可扩展连接器中连接参数变量
- database - 查找 Pervasive 数据库中的所有列
- javascript - 为对象内的键分配一个布尔值
- sql - 右连接后基于包含空值的单行生成多行
- json - 使用 JSON_MODIFY 在 JSON 的开头添加一个元素
- mysql - 在 WooCommerce 中加载商店/产品列表之前更新价格
- javascript - 如何在android中使用javascript和html5打开相机?
- docusignapi - 由于 mime 类型不匹配,来自 https://account-d.docusign.com/error?aspxerrorpath=/oauth/token 的脚本被阻止
- odoo - Odoo中ir作为前缀的含义