使用嵌套for循环填充字典

2024-05-15 20:41:00 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,我的代码是:

import os

root = os.listdir("/path/to/dir")
pic_dir = {}
len_wallpaper = int((24 / (len(root))))

for i in range(24):
    if i<10 :
        pic_dir[(f"{0}{i}")] = root[0]
    else:
        pic_dir[i] = root[0]


print(pic_dir)

电流输出:

{'00': 'file_1', '01': 'file_1', '02': 'file_1', ... '23': 'file1'}

到目前为止,这很好,但我真正想要的是在文件中循环n次,这样它们将添加到列表中n次,然后移动到下一个文件。更像这样:

{'00': 'file_1', '01': 'file_1', '02': 'file_1', ... 
 '07': 'file2', '08': 'file2', ... 
 '22': 'file4', '23': 'file4'}

该目录将保存图片,我的最终目标是创建某种动态墙纸,根据时间进行更改

“len_Wallper”计算文件需要通过此循环运行的次数

这可以通过使用某种嵌套循环来实现吗


Tags: 文件topath代码importlenosdir
3条回答

你的问题是一个X-Y problem。您可以使用列表或更好的^{}对象以更简单的方式显示墙纸图像

在源代码中添加注释,尽可能使用有意义的名称

import os, itertools

# read the filenames of images, count them,  put them in a cycle object
images = os.listdir("/path/to/dir")
n_images = len(images)
images = itertools.cycle(images)

# determine how long, in seconds, a single image will stay on screen
# so that we show all images in 24h
duration = (24*60*60)/n_images 

# IMPORTANT we use a cycle object, the loop body is executed forever or,
# at least, until the program is stopped
for image in images:
    # write yourself wallpaperize & waitseconds 
    wallpaperize(image)
    waitseconds(duration)

下面只是给你一个想法,但本质上设计似乎是错误的,如果你的文件数量超过24个怎么办

counter = 0
for i in range(24):
    if len(str(i)) == 1:
        pic_dir[(f"{0}{i}")] = root[counter]
    else:
        pic_dir[i] = root[counter]
    counter += 1
    if counter > len_wallpaper - 1: 
        counter = 0

如果你想把文件名len_Wallpar times添加到字典中,那很容易(如果你想实现的话)

import os

root = os.listdir("/path/to/directory")
pic_dir = {}
len_wallpaper = int(24/len(root))
count=0
for i in range(24):
    print(root[i])
    for j in range(len_wallpaper):
        print(j)
        if count<10 :
            pic_dir[(f"{0}{count}")] = root[i]
        else :
            pic_dir[f"{count}"] = root[i]
        count+=1



print(pic_dir)

相关问题 更多 >