python - 使用 itertools 进行枚举条件仅获取某些列表索引(python)

标签 python list-comprehension python-itertools enumerate

这是我的代码:

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

最佳答案

尝试这样的事情,

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

关于python - 使用 itertools 进行枚举条件仅获取某些列表索引(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50964812/

相关文章:

python - 将 Python 列表转换为数据框

python - 仅打印奇数字典键及其项

python - 如何加载 Django JSON 以避免与自然键冲突

python - Dataframe 将 float 转换为全小数的字符串

python - 按类型有效地汇总项目

python - 为什么在我的例子中 For 循环比 Map、Reduce 和 List 理解更快

python - 更新列表中的 Python for 循环是如何工作的?

python - 生成 2 个列表的所有组合(玩游戏)

python - 我怎样才能得到字符串的所有可能的 "leet"版本(带有可选替换)?

python - 在 Python 中组合枚举 + itertools.izip