python - 索引列表
问题描述
from typing import List
def up_to_keyword(items: List[str], keyword: str) -> List[str]:
"""Return a new list that contains only the items that occur before keyword
in items, or all items if keyword is not an element of items. Do not
include keyword in your result.
"""
n_list = []
if keyword not in items:
return items
else:
for i in range(len(items)):
if items.index(i) < items.index(keyword):
return n_list.append(i)
我将如何对列表中存在关键字的情况进行编码?我的代码是否接近满足给定条件?
解决方案
from typing import List
def up_to_keyword(items: List[str], keyword: str) -> List[str]:
"""Return a new list that contains only the items that occur before keyword
in items, or all items if keyword is not an element of items. Do not
include keyword in your result.
"""
if keyword not in items:
return items
else
items[:items.index(keyword)] #List slice up to first occurance of keyword
不需要变量 n_list。或者:
from typing import List
def up_to_keyword(items: List[str], keyword: str) -> List[str]:
if keyword in items:
return items[:items.index(keyword)] #List slice up to first occurance of keyword
return items #No need of else
推荐阅读
- c++ - C ++从2个不同的向量中删除shared_ptr
- android - Android openGL ES 3 Vector3f 和 Matrix4f 类的替代品是什么?
- swift - 当我滚动 SwiftUI/Swift 时,图像在列表中消失
- regex - 如何匹配 $ 或 $$ 但如果它们是这些 <$ 和 <$$ 中的任何一个则不匹配
- mysql - 错误:语句需要的资源多于资源队列允许的资源
- c++ - 在 C++ 中检测按键时出现问题
- ggplot2 - 在 R ggplot 中添加一个新的图例
- c# - DBContext - 删除挂起的更改
- javascript - 尝试播放 Tone.js 声音时出现“未定义过滤器”
- 3d - 3D 视图与 2D 视图不匹配