以下是一个示例代码,用于按组别计算向量中的开关数量:
def count_switches_by_group(vector):
switch_count = []
current_switch = None
current_count = 0
for element in vector:
if element == current_switch:
current_count += 1
else:
if current_switch is not None:
switch_count.append((current_switch, current_count))
current_switch = element
current_count = 1
if current_switch is not None:
switch_count.append((current_switch, current_count))
return switch_count
# 测试示例
vector = [1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0]
switch_count = count_switches_by_group(vector)
print(switch_count)
输出结果为:
[(1, 2), (0, 2), (1, 3), (0, 1), (1, 1), (0, 4), (1, 1), (0, 1)]
解释:向量中以相同元素为一组,计算每个组中开关的数量。结果以元组列表的形式返回,每个元组包含开关的值和该组中开关的数量。以上示例中,开关值为1的组有2个开关,开关值为0的组有2个开关,开关值为1的组有3个开关,以此类推。
下一篇:按组别累计计算分类数据的值计数