gpt4 book ai didi

python - 计算数组中的相同元素并创建字典

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:58 27 4
gpt4 key购买 nike

这个问题可能太菜鸟了,但我还是没能弄清楚如何正确地做。

我有一个给定的数组 [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1, 0,2,3](0-5 中的任意元素),我想要一个计数器来计算连续出现零的次数。

1 times 6 zeros in a row
1 times 4 zeros in a row
2 times 1 zero in a row

=> (2,0,0,1,0,1)

因此字典由作为索引的 n*0 个值和作为值的计数器组成。

最终数组包含 500+ 百万个未排序的值,如上所示。

最佳答案

这应该能满足您的需求:

import numpy as np

a = [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3]

# Find indexes of all zeroes
index_zeroes = np.where(np.array(a) == 0)[0]

# Find discontinuities in indexes, denoting separated groups of zeroes
# Note: Adding True at the end because otherwise the last zero is ignored
index_zeroes_disc = np.where(np.hstack((np.diff(index_zeroes) != 1, True)))[0]

# Count the number of zeroes in each group
# Note: Adding 0 at the start so first group of zeroes is counted
count_zeroes = np.diff(np.hstack((0, index_zeroes_disc + 1)))

# Count the number of groups with the same number of zeroes
groups_of_n_zeroes = {}
for count in count_zeroes:
if groups_of_n_zeroes.has_key(count):
groups_of_n_zeroes[count] += 1
else:
groups_of_n_zeroes[count] = 1

groups_of_n_zeroes 持有:

{1: 2, 4: 1, 6: 1}

关于python - 计算数组中的相同元素并创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16341631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com