[英]Issues with an infinitely running while-loop
我有一个程序,它定期下载一组随机文件并检查它们的大小,然后选择一个大小超过给定阈值(当前为 6KB)的文件。
检查工作正常,但如果文件集不包含满足阈值检查的文件,它会一直搜索该文件集,永远。
这是我的代码(function selected chosen()
是在包含文件的目录上返回一个random.choice
,变量z_file
是使用 selected chosen()
的文件,并且size
是一个 function 返回一个get.size
值随机选择的文件) -
threshold = 6000
while True:
z_file = chosen()
file_size = size(z_file)
if file_size < threshold:
print(z_file + " is too small")
else:
break
print(z_file , "is at least 6KB -" , file_size , "bytes ...")
通常它工作正常,但偶尔没有大于 6KB 的文件,结果永远循环 -
PAGE 1 contains [1] images
PAGE 2 contains [1] images
PAGE 3 contains [3] images
pic3_3.png is too small
pic2_1.png is too small
pic3_3.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic1_1.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic3_2.png is too small
pic3_1.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic3_1.png is too small
pic2_1.png is too small
pic3_3.png is too small
pic3_2.png is too small
pic2_1.png is too small
pic3_2.png is too small
pic3_3.png is too small
pic3_3.png is too small
pic3_3.png is too small
我确定我的 while 循环写得不好,我错误地使用了 break 子句,但我无法理解它。 任何帮助/指针将不胜感激。
from collections import defaultdict
threshold = 6000
n = 0
TOTAL_FILES_NUMBER = 3
checked_files = defaultdict(int)
while True:
z_file = chosen()
file_size = size(z_file)
if checked_files[z_file] == 0:
n += 1
checked_files[z_file] = 1
if file_size < threshold:
print(z_file + " is too small")
else:
break
if n == TOTAL_FILES_NUMBER:
break
print(z_file , "is at least 6KB -" , file_size , "bytes ...")
解决这个问题的一种方法是知道你目录中的文件总数(在上面的代码中我假设它总共有 3 个文件)现在问题是你每次选择一个随机文件而你不知道如果您之前选择了它,那么您不能简单地制作一个 integer n
并在每次迭代时递增它,当它达到总数时您只需中断,因为这样您可以检查同一个文件 3 次,它会从循环中中断因为它检查了所有 3 个文件。
因此,为了解决这个问题,我们创建了一个名为checked_files
的dictionary
,它将跟踪每个文件以及我们是否已经选择它,这取决于文件键的值,如果它是 0,那么我们还没有选择该文件,如果它是 1,那么我们之前已经检查过这个文件。
根据这一点,如果我们检查了目录中的所有文件,我们可以使用上面的代码进行检查。
如果您想访问所有文件 random.choice 是个坏主意,我建议 random.shuffle
threshold = 6000
for i in random.shuffle(file_list):
file_size = size(i)
if file_size < threshold:
print(i + " is too small")
else:
print(i , "is at least 6KB -" , file_size , "bytes ...")
break
print("no file above threshold")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.