代码之家  ›  专栏  ›  技术社区  ›  Indrajeet Gour

在python中切片列表项

  •  -1
  • Indrajeet Gour  · 技术社区  · 7 年前

    我已经对需要迭代的字符串元素进行了排序。从列表中的特定元素/项开始到结束。

    我的名单:

    ip_list = ['input1','input2','input3',....,'input10']
    

    例如,我想从任何给定的元素(在每次运行时都是动态的)迭代 input3 目前到列表末尾。

    所以我想实现这样的目标:

    for item in ip_list[input3:]:
        # my logic base
    

    我已经发现,在Python中,我们可以使用位置基(positional base)分割列表,但不能基于值基(valuebase)。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Xantium    7 年前

    是,使用 index() 查找元素在列表中的位置。

    因此,如果您的列表如下所示:

    ip_list = ['input1','input2','input3']
    

    你想从 input3 继续,然后使用 ip_list.index('input3') 返回的位置 输入3 (所以2)。

    然后你只需要以正常的方式分割列表(就像你做的那样 ip_list[2:] )但是使用 索引() :

    for item in ip_list[ip_list.index('input3'):]:
        # my logic base
    

    Finding the index of an item given a list containing it in Python

        2
  •  1
  •   Sebastian Loehner    7 年前

    list[list.index(value):]

    看见 https://docs.python.org/3/tutorial/datastructures.html

    list.index(x[,开始[,结束])

    在值为x的第一个项的列表中返回从零开始的索引。如果没有这样的项,则引发ValueError。

    可选参数start和end在slice符号中解释为,用于将搜索限制在列表的特定子序列中。返回的索引是相对于完整序列的开始而不是起始参数计算的。

        3
  •  0
  •   Aran-Fey Kevin    7 年前

    这里有一个基于 iterators 它适用于任何一个不可重复的项目,而不仅仅是列表:

    def iterate_from(iterable, start_value):
        # step 1: get an iterator
        itr = iter(iterable)
    
        # step 2: advance the iterator to the first matching value
        first_value = next(value for value in itr if value == start_value)
    
        # step 3: yield the remaining values
        yield first_value
        yield from itr
    

    在这里我用了 iter 函数从iterable获取迭代器,以及 next 函数向前移动迭代器。你也可能对 What does the "yield" keyword do? .

    您可以这样使用它:

    ip_list = ['input{}'.format(i) for i in range(1, 11)]
    
    for ip in iterate_from(ip_list, 'input7'):
        print(ip)
    
    # output:
    # input7
    # input8
    # input9
    # input10