Получить первый номер каждого блока дубликатов номеров в списке 0 и 1 - PullRequest
2 голосов
/ 14 мая 2019

У меня есть список, который выглядит следующим образом:

a = [0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0...]

Как мне получить индекс первой 1 в каждом нулевом блоке - один, так что результирующий индекс будет:

[8 23 ..] и т. Д.

Я использовал этот код:

def find_one (a):
    for i in range(len(a)):
        if (a[i] > 0):
            return i
print(find_one(a))

, но он дает мне только первое вхождение 1. Как можно реализовать его для итерации черезвесь список?

Спасибо !!

Ответы [ 4 ]

1 голос
/ 14 мая 2019

Вы можете сделать это, используя zip и все списки:

a = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
r = [i for n,(i,v) in zip([1]+a,enumerate(a)) if v > n]
print(r) # [8,23]
1 голос
/ 14 мая 2019

Поскольку вы пометили pandas, можете использовать groupby.Если s = pd.Series(a), то

>>> x = s.groupby(s.diff().ne(0).cumsum()).head(1).astype(bool)
>>> x[x].index
Int64Index([8, 23], dtype='int64')
0 голосов
/ 14 мая 2019
# `state` is (prev_char, cur_char)
# where `prev_char` is the previous character seen
# and `cur_char` is the current character
#
#
# (0, 1) .... previous was "0"
#             current is "1"
#             RECORD THE INDEX.
#             STRING OF ONES JUST BEGAN
#
# (0, 0) .... previous was "0"
#             current is "0"
#             do **NOT** reccord the index
#
# (1, 1) .... previous was "1"
#             current is "1"
#             we are in a string of ones, but
#             not the begining of it.
#             do **NOT** reccord the index.
#
# (1, 0)....  previous was "1"
#             current is "0"
#             string of ones, just ended
#             not the start of a string of ones.
#             do **NOT** reccord the index.


state_to_print_decision = dict()
state_to_print_decision[(0, 1)] = True

def find_one (a, state_to_print_decision):
    #
    # pretend we just saw a bunch of zeros
    # initilize state to (0, 0)
    state = (0, 0)

    for i in range(len(a)):
        #
        # a[i] is current character
        #
        # state[0] is the left element of state
        #
        # state[1] is the right elemet of state
        #
        # state[1] was current character,
        #          is now previous character
        #        
        state = (state[1], a[i])

        it_is_time_to_print = state_to_print_decision.get(state, False)

        if(it_is_time_to_print):
            indicies.append()  

    return indicies

a =  [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
print(find_one(a, state_to_print_decision))
0 голосов
/ 14 мая 2019

без панд:

b = a[1:]
[(num+1) for num,i in enumerate(zip(a,b)) if i == (0,1)]
...