嵌套循环,查找出列表里重复字符,保存到新的列表(实际工作中可能应用到 筛选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)

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

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值