需求:
python实现一个线程类,初始化有个字段old_list = [1,2,3],有个方法每隔5秒随机生成三个1~10 的数字存放在一个列表new_list 中,old_list与new_list对比,求差异;
代码:
import threading
import time
import random
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self.old_list = [1, 2, 3]
def run(self):
while True:
time.sleep(5)
self.new_list = [random.randint(1, 10) for _ in range(3)]
self.find_differences()
def find_differences(self):
differences = [item for item in self.new_list if item not in self.old_list] + \
[item for item in self.old_list if item not in self.new_list]
if differences:
print(f"差异为: {differences}")
else:
print("没有差异")
# 使用示例
my_thread = MyThread()
my_thread.start() # 启动线程
# 注意:此代码将无限循环运行,除非线程被中断或程序被停止。
log
差异为: [6, 5, 6, 1, 2, 3]
差异为: [10, 10, 2, 3]
差异为: [10, 7, 5, 1, 2, 3]
差异为: [5, 9, 1, 3]
差异为: [6, 2]
差异为: [9, 4, 8, 1, 2, 3]
差异为: [6, 8, 1, 3]
差异为: [10, 2]
差异为: [7, 10, 10, 1, 2, 3]
差异为: [4, 7, 2, 3]
差异为: [8, 2]
差异为: [7, 9, 1, 2]
差异为: [10, 7, 9, 1, 2, 3]
差异为: [6, 4, 2, 3]
差异为: [6, 8, 1, 3]
差异为: [9, 8, 5, 1, 2, 3]
差异为: [10, 3]
差异为: [8, 5, 10, 1, 2, 3]
差异为: [6, 6, 2, 3]
差异为: [10, 8, 10, 1, 2, 3]
差异为: [4, 7, 9, 1, 2, 3]
差异为: [6, 4, 10, 1, 2, 3]
延伸优化:
- 差异列表中存在重复值,去重;
- 将差异list为old_list赋值;
总的需求:
python实现一个线程类,初始化有个字段old_list = [1,2,3],有个方法每隔5秒随机生成三个1~10 的数字存放在一个列表new_list 中,old_list与new_list对比,求差异并去重,如果有差异,则将差异的结果为old_list赋值,如何实现 给出代码
import threading
import time
import random
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self.old_list = [1, 2, 3]
def run(self):
while True:
time.sleep(5)
self.new_list = [random.randint(1, 10) for _ in range(3)]
print("New list:", self.new_list)
self.find_differences()
def find_differences(self):
# 创建一个集合以去重
old_set = set(self.old_list)
new_set = set(self.new_list)
# 找出差异
differences = old_set.symmetric_difference(new_set)
# 如果存在差异,则更新old_list
if differences:
self.old_list = list(differences)
print(f"差异为: {differences}")
print(f"更新后的old_list: {self.old_list}")
else:
print("没有差异")
# 使用示例
my_thread = MyThread()
my_thread.start() # 启动线程
# 注意:此代码将无限循环运行,除非线程被中断或程序被停止。
log
New list: [3, 1, 10]
差异为: {2, 10}
更新后的old_list: [2, 10]
New list: [6, 6, 5]
差异为: {2, 10, 5, 6}
更新后的old_list: [2, 10, 5, 6]
New list: [9, 5, 3]
差异为: {2, 3, 6, 9, 10}
更新后的old_list: [2, 3, 6, 9, 10]
New list: [10, 2, 7]
差异为: {3, 6, 7, 9}
更新后的old_list: [3, 6, 7, 9]
New list: [8, 10, 5]
差异为: {3, 5, 6, 7, 8, 9, 10}
更新后的old_list: [3, 5, 6, 7, 8, 9, 10]
New list: [6, 4, 10]
差异为: {3, 4, 5, 7, 8, 9}
更新后的old_list: [3, 4, 5, 7, 8, 9]
New list: [3, 2, 5]
差异为: {2, 4, 7, 8, 9}
更新后的old_list: [2, 4, 7, 8, 9]
New list: [7, 10, 6]
差异为: {2, 4, 6, 8, 9, 10}
更新后的old_list: [2, 4, 6, 8, 9, 10]
New list: [7, 10, 10]
差异为: {2, 4, 6, 7, 8, 9}
......