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