用嵌套的for循环填充字典

时间:2020-01-12 11:13:15

标签: python python-3.x dictionary

到目前为止,我的代码:

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_wallpaper”计算文件需要通过此循环运行的次数。

这可以通过使用某种嵌套循环来完成吗?

4 个答案:

答案 0 :(得分:2)

以下只是给您一个想法,但实际上设计似乎是错误的,如果文件数超过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

答案 1 :(得分:2)

如果您想将文件名len_wallpaper次添加到字典中,这很容易(如果那是您要实现的目标)

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)

答案 2 :(得分:2)

您的问题是X-Y problem。您可以使用列表或更好的itertools.cycle对象,以更简单的方式显示墙纸图像。

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

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)

答案 3 :(得分:1)

考虑到实现目标的设计有些缺陷,我建议以一种方法来实现它,该函数将墙纸的图像文件的所有路径都放在一个列表中,并随着时间的推移遍历该列表,如图所示。下方:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import itertools
from threading import Timer

# put more image file extensions here if you want
VALID_IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg"]

DIRECTORY_WALLPAPERS = "/path/to/dir"

def FileFilterForImages(entry: str) -> bool:
    filename, extension = os.path.splittext(entry)
    extension = extension.lower() # sometimes extension names are made up of capital characters
    return extension in VALID_IMAGE_EXTENSIONS

def FindAllWallpapers(path: str) -> list:
    list_of_image_files = []
    for rootdir, dirs, files in os.walk(path): # walks through the entire tree below specific directory
        for file in files:
            if FileFilterForImages(file):
                list_of_image_files.append(file)
    # according to @gboffi[user:2749397], i replace the list with iterator :)
    return list_of_image_files

def DisplayWallpaper(path: str):
    pass # TODO to be implemented
    # i'm curious about how to change wallpapers on Windows with python
    # so i googled a little
    # @see: https://stackoverflow.com/questions/1977694/how-can-i-change-my-desktop-background-with-python

def GetWallpaperIterator():
    list_of_image_files = FindAllWallpapers(DIRECTORY_WALLPAPERS)
    return itertools.cycle(list_of_image_files)

def OnTimer():
    for image_file_path in GetWallpaperIterator():
        DisplayWallpaper(image_file_path)

if __name__ == "__main__":
    image_files = FindAllWallpapers(DIRECTORY_WALLPAPERS)
    time_interval_for_each_wallpaper = 60 # seconds
    # this means each wallpaper will stay on screen
    # for 60 seconds before getting changed

    # [Timer Object](https://docs.python.org/3.9/library/threading.html#timer-objects)
    # use threading.Timer instead of time.sleep
    timer = Timer(interval=time_interval_for_each_wallpaper, function=OnTimer)
    timer.start() # start the automaton !!!