How to get index and appearance of each element using itertools.groupby ()

In this story, I have two lists:

list_one=[1,2,9,9,9,3,4,9,9,9,9,2]
list_two=["A","B","C","D","A","E","F","G","H","Word1","Word2"]

I want to find consecutive 9 pointers in list_one so that I can get the corresponding line from list_two, I tried:

group_list_one= [(k, sum(1 for i in g),pdn.index(k)) for k,g in groupby(list_one)]

I was hoping to get the index of the first 9 in each tuple, and then try from there from there, but that didn't work.

What can i do here? PS: I looked at the itertools documentation, but it seems very vague to me. thanks in advance

EDIT: Expected Result (key, events, index_of_first_occurance) something like

[(9, 3, 2), (9, 4, 7)]
+4
source share
4 answers

Judging by your expected result, try:

from itertools import groupby

list_one=[1,2,9,9,9,3,4,9,9,9,9,2]
list_two=["A","B","C","D","A","E","F","G","H","Word1","Word2"]
data = zip(list_one, list_two)
i = 0
out = []

for key, group in groupby(data, lambda x: x[0]):
        number, word = next(group)
        elems = len(list(group)) + 1
        if number == 9 and elems > 1:
            out.append((key, elems, i))
        i += elems

print out

:

[(9, 3, 2), (9, 4, 7)]

:

[(9, 3, 'C'), (9, 4, 'G')]

:

from itertools import groupby

list_one=[1,2,9,9,9,3,4,9,9,9,9,2]
list_two=["A","B","C","D","A","E","F","G","H","Word1","Word2"]
data = zip(list_one, list_two)
out = []

for key, group in groupby(data, lambda x: x[0]):
    number, word = next(group)
    elems = len(list(group)) + 1
    if number == 9 and elems > 1:
        out.append((key, elems, word))

print out
+5

, oneliner. , .

. , , itertools.groupby. groupby . , .

[(key, len(list(it))) for (key, it) in itertools.groupby(list_one)]

, . oneliner . , - reduce.

, reduce , . , reduce(lambda x,y: x*y, [2,3,4]) 2 * 3 = 6, 6 * 4 = 24 24. , x .

- + . , [(0,0,0)] . ( ).

reduce(lambda lst,item: lst + [(item[0], item[1], lst[-1][1] + lst[-1][-1])], 
       [(key, len(list(it))) for (key, it) in itertools.groupby(list_one)], 
       [(0,0,0)])[1:]

, , .

reduce(lambda lst,item: lst + [(item[0], item[1], sum(map(lambda i: i[1], lst)))],
       [(key, len(list(it))) for (key, it) in itertools.groupby(list_one)], [])

, . 9, filter:

filter(lambda item: item[0] == 9, ... )
+3

, , :

g = groupby(enumerate(list_one), lambda x:x[1])
l = [(x[0], list(x[1])) for x in g if x[0] == 9]
[(x[0], len(x[1]), x[1][0][0]) for x in l]

[(9, 3, 2), (9, 4, 7)]
+2

, , .

element_index = 0 #the index in list_one of the first element in a group
for element, occurrences in itertools.groupby(list_one):
    count = sum(1 for i in occurrences)
    yield (element, count, element_index)
    element_index += count

If you want to exclude a variable element_index, think about what the cumulative_sum function should do, where this value depends on all previous values ​​that have been iterated.

+1
source

Source: https://habr.com/ru/post/1536189/


All Articles