首页 > 解决方案 > 索引列表

问题描述

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)

我将如何对列表中存在关键字的情况进行编码?我的代码是否接近满足给定条件?

标签: 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.
"""

    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      

推荐阅读