python - 有没有更好的方法来检查按顺序更改的值?

标签 python python-3.x

我有一个如下所示的列表:

list = ['A', 'A', 'B', 'A', 'B', 'A', 'B']

而且,我想在其他值(“B”)到来之前连续计算第一个值(在上述情况下为“A”)的数量。

所以我写了这样的代码:

history = list[0]
number_A = 0
number_B = 0
for i in list:
    if history != i:
        break

    if i == 'A':
        number_A += 1
        history = 'A'
    else:
        number_B += 1
        history = 'B'

但是,我认为这很不整洁。 有没有更简单的方法来完成这个过程?

感谢阅读。

最佳答案

使用 groupby使用默认的按键功能,可以统计第一条石斑鱼的元素数量:

from itertools import groupby

def count_first(lst):
    if not lst:
        return 0
    _, grouper = next(groupby(lst))
    return sum(1 for _ in grouper)

print(count_first(['A', 'A', 'B', 'A', 'B', 'A', 'B']))  
# 2

关于python - 有没有更好的方法来检查按顺序更改的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596975/

相关文章:

python - 如何根据列值的范围将单个数据帧拆分为多个数据帧?

python-3.x - 非拉丁字符的 Python 正则表达式不起作用

python - "python -m doctest"忽略不同目录下的同名文件

python - [如何使用 cmd 从 sublime text 3 运行代码]

python - 使用编号在 python 中列表理解

python - 使用 Python 2 运行的 Pylint 检查 Python 3 源代码

python - 如何根据输入创建不同的对象?

python - 无法在 Python 中加载程序集 'Microsoft​.VisualStu​dio.TestTo​ols.UITest​ing'

python - Python 3 中的 `raw_input()` 和 `input()` 有什么区别?

使用 UTF-8 字符串写入文件时出现 Python 编解码器错误