【问题标题】:Search list between specific index in PythonPython中特定索引之间的搜索列表
【发布时间】:2016-09-20 08:33:56
【问题描述】:

我需要创建一个函数来搜索特定索引之间的列表项。

我想有一个列表的开始和停止索引,我想找到项目在列表中的位置。

例如:

def find(list, word, start=0, stop=-1):
    print("In function find()")

    for item in list:
        if item == word:
            return list[start:stop].index(word)

n_list = ['one', 'five', 'three', 'eight', 'five', 'six', 'eight']
print(find(n_list, "eight", start=4, stop=7 ))

此代码将返回“2”,因为单词“八”在 list[4:7] 中 2 的索引位置。

我的问题:如何更改此代码以使其返回“6”?如果我删除 [4:7],它会给我“3”,因为“8”这个词也在 [3] 位置。

编辑:忘了说谢谢!

【问题讨论】:

  • 你总是想得到你单词的最后一个索引吗?
  • 该函数返回“2”,因为您正在调用list[start:stop] 上的索引,它本身就是一个列表

标签: python list loops search


【解决方案1】:

不需要for 循环:

def find(list, word, start=0, stop=-1)
    '''Find word in list[start:stop]'''
    try:
       return start + list[start:stop].index(word)
    Except ValueError:
       raise ValueError("%s was not found between indices %s and %s"%(word, start, stop))

【讨论】:

    【解决方案2】:

    如果您假设以startstop 为特征的范围是可以信任的,则可以将其设为单行:

    n_list[start:stop].index(word)+start
    

    【讨论】:

    • 如果元素不在切片中,这将抛出 ValueError,因此您可能希望将其包装到 try/except 中。否则很好。
    • @tobias_k if stop > len(list): return 怎么样?
    【解决方案3】:

    你不能简单地添加开始吗?

    def find(list, word, start=0, stop=-1):
    print("In function find()")
    
    for item in list:
        if item == word:
            return start + list[start:stop].index(word)
    

    【讨论】:

    • 注意:如果word 在列表中但在切片之外,这将失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多