[英]How to count the number of times same number has appeared in a list in python?
I have a list of about 75000 which contain random sequence of +1s and -1s.我有一个大约 75000 的列表,其中包含 +1 和 -1 的随机序列。 I want to count how many time +1 has appeared one time and two times and three times and so on.我想数一数+1出现了多少次,一次,两次,三次等等。 So goes for the -1s. -1s也是如此。
For example My_list = [1,1,1,-1,-1,1,1,1,-1,-1,1,-1,1...]例如 My_list = [1,1,1,-1,-1,1,1,1,-1,-1,1,-1,1...]
expected output would be: (1:1x2,2x0,3x2|-1:1x1,2x2}) in words:+1 repeated once 2 times, twice 0 times, thrice repeated 2 times -1 repeated once 1 time, twice 2 times预期输出将是:(1:1x2,2x0,3x2|-1:1x1,2x2}) 换句话说:+1 重复一次 2 次,两次 0 次,三次重复 2 次 -1 重复一次 1 次,两次 2 次
Thank you谢谢
I am very new to python learning it especially for my trading project.我对 python 非常陌生,尤其是对于我的交易项目。 I cant go further than counting the total number occurrence of a given value rather than counting the repeated number of occurrence除了计算给定值的总出现次数而不是计算重复出现的次数,我不能走得更远
Approach方法
Code代码
from itertools import groupby
from collections import Counter
def run_stats(lst):
def rle(lst):
' Run length encoding of the runs (value, runlength) '
return [(key, len(list(group))) for key, group in groupby(lst)]
# Count of (value, runlength) pairs
cnts = Counter(rle(lst))
# Aggregate runs of +1/-1 tuples in lists
stats = {1:[], # +1 run pairs
-1:[]} # -1 run pairs
for tup, cnt in cnts.items():
val, runlength = tup
stats[val].append((runlength, cnt))
return stats
Usage用法
# Test Data
lst = [1,1,1,-1,-1,1,1,1,-1,-1,1,-1,1]
# Generate result
results = run_stats(lst)
# Format Output (using JamieDoombos formatting)
for val in results:
print(f'{val}:', ','.join(f'{run}x{count}' for run, count in results[val]))
Output输出
1: 3x2,1x2
-1: 2x2,1x1
I suggest iterating over the list using an index, and for each new item, count the occurrences and store the result in a dict.我建议使用索引遍历列表,对于每个新项目,计算出现次数并将结果存储在字典中。
The resulting runs
dict in this code has the list domain (-1, 1) as keys.此代码中生成的runs
字典将列表域 (-1, 1) 作为键。 Each value in the dict is another dict with the run lengths as keys, and the number of occurrences of the run length as values. dict 中的每个值都是另一个 dict,其中游程长度作为键,游程长度的出现次数作为值。
from collections import defaultdict
My_list = [1,1,1,-1,-1,1,1,1,-1,-1,1,-1,1]
# map of values to a map of lengths to the number of occurrences
runs = defaultdict(lambda: defaultdict(int))
list_length = len(My_list)
index = 0
while index < list_length:
item = My_list[index]
run_length = 1
index += 1
while index < list_length and My_list[index] == item:
index += 1
run_length += 1
runs[item][run_length] += 1
for value, value_runs in runs.items():
print(f'{value}:', ','.join(f'{run}x{count}' for run, count in value_runs.items()))
Result:结果:
1: 1x2,2x0,3x2
-1: 1x1,2x2,3x0
EDIT: this uses a defaultdict that handles any number of consecutive values and values outside the domain.编辑:这使用 defaultdict 处理任意数量的连续值和域外的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.