简体   繁体   English

如何计算相同数字在python列表中出现的次数?

[英]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方法

  • Using groupby to find runs使用groupby查找运行
  • Using Counter to count runs of value +1/-1使用Counter计算值 +1/-1 的运行次数

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.

相关问题 python计数日期出现的次数 - python count number of times the date has appeared 计算 Python 列表中数字增加的次数 - Count number of times the numbers are increasing in Python list 如何计算列表中的数字大于其后的数字的次数? - How to count the number of times a number in a list is greater than the number after it? 如何计算数组python中连续出现的值的次数? - How to count how many times values has appeared continuously in array python? 如何正确显示特定单词在用户给定输入中出现的次数? - How to correctly display the number of times a particular word has appeared in the user given input? 如何计算一个术语在JSON对象列表的值中出现的次数? - How do I count the number of times a term has occured in the values of a list of JSON objects? 如何连续检查列表中的数字是否发生了特定次数 - How to check if a number has occurred a particular number of times in a list consecutively 在我的 python 程序中,我如何计算一个值出现的次数 - In my python program how do I count the number of times a value has occurred 如何使用.count计算一个列表中每个项目出现在python中另一个列表中的次数? - How to use .count to calculate number of times each item in one list appears in another list in python? 如何计算python列表中单独列表中的数字? - How to count number in separate list in a list for python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM