Этот ответ предполагает, что вы пытаетесь подсчитать только переходы и не пытаетесь отображать значения (последний абзац вопроса).
Если вы имеете дело только с набором {-1, 0, 1}
, возможно, вы можете суммировать значения из списка. Это немного быстрее, чем добавить их в счетчик и дает вам информацию о переходе.
И, конечно, проще не суммировать полный список каждый раз, а просто увеличивать / уменьшать счетчик внутри вашего логического блока, когда происходят изменения.
more_ones = True if sum(my_list) > 0 else False
transition_counter = 0
transitions_history = []
for x in range(0, 100):
# some rules, which change mylist
# you can place a transition counter logic right here
current_sum = sum(my_list) # one more time, counting inside the logic is faster
if current_sum < 0 and more_ones:
transition_counter += 1
more_ones = False
transitions_history.append(x)
elif current_sum > 0 and not more_ones:
transition_counter += 1
more_ones = True
transitions_history.append(x)
здесь я предполагаю, что если сумма не пересекает ноль, то перехода нет.
Подобный подход работает в префакторном случае (если я правильно понял идею):
my_list = [0, 1, -1, -1] # sample data
factor = 1.5 # some factor
pos_count = my_list.count(1)
neg_count = my_list.count(-1)
more_ones = True if pos_count > factor * neg_count else False # unclear part - don't know what you plan to do with zeroes
transition_counter = 0
transitions_history = []
for x in range(0, 100):
# I provide a test logic
### CROP HERE ###
try:
if x < 3:
my_list.remove(-1) # better to decrement/increment pos. and neg. counts here
elif x >= 3 and x < 5:
my_list.append(1)
elif x >= 5 and x < 10:
my_list.append(-1)
else:
my_list.append(1)
except ValueError:
pass
### CROP HERE ###
pos_count = my_list.count(1)
neg_count = my_list.count(-1)
if neg_count > pos_count * factor and more_ones:
transition_counter += 1
more_ones = False
# you couldn't store list and need a copy, otherwise it will change values by pointer
transitions_history.append((x, 'pos_to_neg', [i for i in my_list]))
elif pos_count > neg_count * factor and not more_ones:
transition_counter += 1
more_ones = True
transitions_history.append((x, 'neg_to_pos', [i for i in my_list]))
Пример вывода:
transitions_history
Out:
[(1, 'neg_to_pos', [0, 1]),
(9, 'pos_to_neg', [0, 1, 1, 1, -1, -1, -1, -1, -1]),
(14, 'neg_to_pos', [0, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1])]
transition_counter
Out:
3