嵌套循环,查找出列表里重复字符,保存到新的列表(实际工作中可能应用到 筛选txt、Excel文档中重复数据,并保存到新的文档)

嵌套循环,查找出列表里重复字符,保存到新的列表(实际工作中可能应用到 筛选txt、Excel文档中重复数据,并保存到新的文档)

duplicate_lines = ['1200001\n', '1233331\n', '125681\n']

result = []

for line in duplicate_lines:
    current_char = None#表示当前的字符为空
    count = 0#记录连续重复字符的数量
    consecutive_duplicates = ""#用于存储连续重复的字符
    for char in line:
        if char == current_char:
            count += 1
            consecutive_duplicates += char
        else:#如果当前字符char与前一个字符current_char不相同
            if count > 1:
                result.append(line)  # 将整行添加到result列表中
             
            current_char = char#将current_char更新为当前字符char,以便继续跟踪下一个字符
            count = 1#将count重置为1,表示当前字符是一个新的字符序列的开始
            consecutive_duplicates = char

    #if count > 1:
        #result.append(line)  # 将整行添加到result列表中

print(result)

打印结果:
[‘1200001\n’, ‘1233331\n’]

优化代码:

def find_repeated_chars(text):
    result = []
    for line in text:
        prev_char = None
        count = 1
        consecutive_duplicates = ""
        for char in line:
            if char == prev_char:
                count += 1
                consecutive_duplicates += char

            else:
                if count > 1:
                    result.append(line)
                count = 1
                prev_char = char
                consecutive_duplicates = char

        #if count > 1:
            #result.append(line)
    #return result
    print(result)    
if __name__ == '__main__'   :
    text = ['1200001\n', '1233331\n', '125681\n']
    find_repeated_chars(text=text)

循环部分 运行逻辑步骤:
在这里插入图片描述

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-09 17:22:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-09 17:22:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-09 17:22:03       82 阅读
  4. Python语言-面向对象

    2024-01-09 17:22:03       91 阅读

热门阅读

  1. 《微信小程序开发从入门到实战》学习七十六

    2024-01-09 17:22:03       46 阅读
  2. Ubuntun构建本地源详细教程

    2024-01-09 17:22:03       60 阅读
  3. 【笔记】用Python做手机多平台UI应用

    2024-01-09 17:22:03       52 阅读