【问题标题】:Using itertools for a condition with enumerate to only get certain list indexes (python)将 itertools 用于具有枚举的条件以仅获取某些列表索引(python)
【发布时间】:2018-06-21 09:16:28
【问题描述】:

这是我的代码:

from itertools import tee, islice, chain

def previous_and_next(some_iterable):
   prevs, items, nexts = tee(some_iterable, 3)
   prevs = chain([None], prevs)
   nexts = chain(islice(nexts, 1, None), [None])
   return zip(prevs, items, nexts)

fruits = ['watermelon', 'apple', 'apple', 'banana', 'kiwi', 'peach', 'apple',
          'pear', 'watermelon', 'apple', 'apple', 'orange', 'apple', 'grape']

nr_of_apples = 0
apples = []

for previous, item, nxt in previous_and_next(fruits):
    apple_indexes = [i for i, x in enumerate(fruits) if x == 'apple' and nxt != 'apple']
print(apple_indexes)

for i in apple_indexes:
    index = i - 1
    for previous, item, nxt in previous_and_next(fruits[index:]):
        if nxt != 'apple':
            break
        apples.append(nxt)

nr_of_apples = len(apples)

print(nr_of_apples)

我正在尝试使用 itertools 计算单词“apples”出现在列表中的次数。 我知道这是一种复杂的做事方式,可以通过这种更简单的方式实现:

for f in fruits:
    if f == 'apple':
        apples.append(f)

但这里的想法是扩展此代码,以便与斯坦福 CoreNLP 的命名实体识别一起更复杂地使用。 所以我从简单开始,然后逐步实现。

问题是我的代码目前正在返回:

[1, 2, 6, 9, 10, 12]  # indexes of the apples
8  # number of apples

显然列表中没有 8 个苹果,只有 6 个。所以我的问题是,如何在枚举中添加条件 函数只获取不跟随另一个苹果的苹果的索引? 所以输出应该是这样的:

[1, 6, 9, 12]
6

【问题讨论】:

    标签: python list-comprehension itertools enumerate


    【解决方案1】:

    试试这样的,

    In [160]: list_of_index = [i for i,j in enumerate(fruits) if j == 'apple']
    
    In [161]: print list(set([min(i) if i[1] - i[0] == 1 else max(i) for i in zip(list_of_index,list_of_index[1:])]))
    [1, 12, 6, 9]
    
    In [162]: print fruits.count('apple')
    6
    

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 2016-12-08
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多