我有一个程序,定期下载一组随机文件并检查它们的大小,然后选择一个大小超过给定阈值的文件(当前为6KB)。
检查工作正常,但是如果文件集中没有满足阈值检查的文件,它就会一直在该集合中搜索,永远搜索。
下面是我的代码(函数chosen()是在目录上返回带有文件的random.choice,变量z_file是使用chosen() func选择的文件,size是为随机选择的文件返回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循环写得很糟糕,而且我使用but子句的方法不正确,但是我无法理解它。如有任何协助/指示,将不胜感激。
发布于 2022-01-15 13:04:35
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个文件),现在的问题是,您每次都选择一个随机文件,并且您不知道以前是否选择了它,所以您不能简单地在每次迭代中生成一个整数n并增加它,并且当它达到您所破坏的总数时,因为您可以检查同一个文件3次,它将从循环中中断,因为它已经检查了所有3个文件。
因此,为了解决这个问题,我们创建了一个名为dictionary的checked_files,它将跟踪每个文件,以及我们是否已经选择了它,这取决于文件键的值,如果是0,那么我们没有选择该文件,如果它是1,那么我们之前已经检查过这个文件。
根据这一点,如果我们检查了目录中的所有文件,我们可以使用上面的代码进行检查。
发布于 2022-01-15 13:20:55
如果您想访问所有的文件,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")https://stackoverflow.com/questions/70721678
复制相似问题