python - 计算列表中相邻重复元素的数量

标签 python python-3.x

我的期望:

input = ["a", "a", "a", "c", "b", "b", "c"]
output: ['a', '3', 'c', '1', 'b', '2', 'c', '1']

我的代码:

lst = ["a", "a", "a", "c", "b", "b", "c"]

result = []
index = 0

while(index < len(lst)-1):
    count = 1
    result.append(lst[index])
    while(lst[index] == lst[index+1]):
        count += 1
        index += 1

    result.append(str(count))
    index += 1
    print("step: ", result)

print("result: ", result) 

我得到了什么:

step:  ['a', '3']
step:  ['a', '3', 'c', '1']
step:  ['a', '3', 'c', '1', 'b', '2']
result:  ['a', '3', 'c', '1', 'b', '2']

我无法正确计算最后一个元素。

这是另一个输入:

['East', 'East', 'East', 'East', 'East', 'West', 'West', 'West', 'West', 'North', 'South', 'West', 'West', 'West', 'North', 'South', 'West', 'West', 'West', 'North', 'North', 'West', 'West', 'West', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'South', 'South', 'East', 'East', 'East', 'North', 'North', 'East', 'East', 'South', 'South', 'South', 'South', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West']

最佳答案

您的代码未考虑列表中的最后一项,因为您要避免在评估lst[index] == lst[index+1]时出现索引越界错误。通过使用 while(index < len(lst)-1): 迭代比列表长度小 1 的范围.

一个无需在循环后重复计数代码的简单解决方法是首先无条件地将虚拟项附加到列表中,如果您仍然需要完整的原始列表,则可以选择在计数完成后弹出它。下面的示例使用 object 的实例作为虚拟项目,因为它有助于确保 lst[index] == lst[index+1] 的最后评估永远不会是True :

lst.append(object()) # append a dummy item first
while(index < len(lst)-1):
    count = 1
    result.append(lst[index])
    while(lst[index] == lst[index+1]):
        count += 1
        index += 1

    result.append(str(count))
    index += 1
    print("step: ", result)

lst.pop() # add this line only if you still need the original lst for later use

关于python - 计算列表中相邻重复元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68900847/

相关文章:

python - 将帧合并为一个视频时如何避免系统死机

python - matplotlib 填充箱线图的边框颜色

python - 根据列中找到的阈值向上移动 DataFrame 列

python - 如何向按钮添加 Shift-Click 选项

python - OperatorNotAllowedInGraphError : using a `tf.Tensor` as a Python `bool` is not allowed: (error in tf Cycle GAN)

python - 如何从 tkinter 输入框中获取整数?

python - 如何根据第一次出现的唯一列值获取行

python - 从同一文件夹中的文件导入功能

python - 空路径与这些中的任何一个都不匹配

python - 将列插入 Pandas 数据框