【问题标题】:populating a dictionary with nested for loop用嵌套的 for 循环填充字典
【发布时间】:2020-01-12 11:13:15
【问题描述】:

到目前为止我的代码:

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

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

【问题讨论】:

  • 不太清楚,所以root 目录是文件列表,对吧?为什么需要嵌套?
  • 我已经稍微编辑了我的问题,我希望这能让我更清楚地了解我的最终目标。
  • 我不明白,你的代码中的int((24 / (len(root)))) 有意义吗?
  • 所以这是壁纸转换之间的时间间隔。那么24 的单位是什么?分钟还是秒?
  • 我觉得这个设计从一开始就有缺陷,你为什么不把壁纸的所有文件名放到一个列表中,随着时间的推移循环遍历列表?

标签: python python-3.x dictionary


【解决方案1】:

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

【讨论】:

  • 谢谢你,是的,我的设计有缺陷,需要重新考虑。
【解决方案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)

【讨论】:

    【解决方案3】:

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

    将 cmets 放入源代码中,尽可能使用有意义的名称...

    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)
    

    【讨论】:

      【解决方案4】:

      考虑到你实现目标的设计有点瑕疵,我建议用一个函数将壁纸图像文件的所有路径放在一个列表中,并随着时间的推移遍历列表,如图所示下面:

      #!/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 !!!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2015-01-09
        • 2020-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多