【问题标题】:Is there a way to get the next item in a list by knowing the current item's value?有没有办法通过知道当前项目的值来获取列表中的下一个项目?
【发布时间】:2012-10-20 13:19:19
【问题描述】:
my_list = ['apple', 'pear', 'orange', 'raspberry']

# I know that I'm always looking for pear.
print 'pear' in my_list # prints True

# I want to be able to get a key by its value.
pear_key = my_list['pear'].key # should be 1

# Print the next item in the list.
print my_list[pear_key + 1] # should print orange

我知道pear 将始终是我列表中的一个项目(虽然不是位置),我正在寻找一种方法来获取该列表中下一个项目的值,或者通过获取当前键通过了解它的价值并将其提升一个(就像我在上面的示例中所做的那样)或使用类似 my_list.next 的东西。

【问题讨论】:

    标签: python list key


    【解决方案1】:
    try:
        pos = my_list.index('pear')
        print my_list[pos + 1]
        # orange
    except IndexError as e:
        pass # original value didn't exist or was end of list, so what's +1 mean?
    

    您当然可以通过使用(认为它可能是 itertools 对配方)预先缓存它

    from itertools import tee
    fst, snd = tee(iter(my_list))
    next(snd, None)
    d = dict(zip(fst, snd))
    

    但是你会忘记它是否在原始列表中,或者只是没有一个合乎逻辑的下一个值。

    【讨论】:

      【解决方案2】:

      使用这个:

      >>> my_list[my_list.index('pear') + 1]
      'orange'
      

      请注意,如果这是列表中的最后一个值,则会收到异常 IndexError

      【讨论】:

        【解决方案3】:

        虽然给出了最简单的解决方案,但如果您想在通用迭代器而不是列表上执行此操作,最简单的答案是使用itertools.dropwhile()

        import itertools
        
        def next_after(iterable, value):
            i = itertools.dropwhile(lambda x: x != value, iterable)
            next(i)
            return next(i)
        

        可以这样使用:

        >>> next_after(iter(my_list), "pear")
        'orange'
        

        请注意,如果您正在处理列表,这是一个较慢且可读性较差的解决方案。这只是另一种情况的说明。

        您还可以生成具有更多描述性错误的版本:

        def next_after(iterable, value):
            i = itertools.dropwhile(lambda x: x != value, iterable)
            try:
                next(i)
            except StopIteration:
                raise ValueError("{} is not in iterable".format(repr(value)))
            try:
                return next(i)
            except StopIteration:
                raise ValueError("{} is the last value in iterable".format(repr(value)))
        

        【讨论】:

          【解决方案4】:

          您可以在列表中使用index 来查找特定值:-

          try:
              print my_list[my_list.index('pear') + 1]
          except (IndexError, ValueError), e:
              print e
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-12-25
            • 2011-02-19
            • 1970-01-01
            • 2020-05-05
            • 2017-06-23
            • 2021-07-09
            • 1970-01-01
            相关资源
            最近更新 更多