【问题标题】:if item in list match item in list from child element in dictionary如果列表中的项目与字典中子元素的列表中的项目匹配
【发布时间】:2015-05-25 15:12:27
【问题描述】:

python 新手,已经准备好了,希望能帮上忙。

testn1 = {'names':('tn1_name1','tn1_name2','tn1_name3'),'exts':('.log','.txt')}
testn2 = {'names':('tn2_name1'),'exts':('.nfo')}
testnames = {1:testn1,2:testn1}

directory = 'C:\\temp\\root\\'

for subdir in os.listdir(directory):

  # check if name of sub directory matches the name in any of the dicts in testnames[testn*]['names']
  if os.path.isdir(os.path.join(directory, subdir)) and [subdir in subdir.lower() in testnames[testn1]['names']]: # this  works but need to iterate through all dicts
    print(subdir)

    # if the a dir name matches do a recursive search for all filenames that exist in the same dict with the corresponding extensions
    for dirname, dirnames, filenames in os.walk(os.path.join(directory, subdir)):
      for file in filenames:
        if file.endswith(testnames[testn1]['exts']): # this works but need to match with corresponding folder 
          print(file)

我认为我可以做这样的事情,但我确信我对 python 的理解不是必须的。

if os.path.isdir(os.path.join(directory, subdir)) and [subdir in subdir.lower() in [for testnames[key]['names'] in key, value in testnames.items()]]:

我希望保持这种结构,但对任何事情都持开放态度。

编辑:我最终选择了...

if os.path.isdir(os.path.join(directory, subdir)) and [i for i in testnames.values() if subdir.lower() in i['names']]:

感谢 @pzp1997 对 .values() 的提示

【问题讨论】:

    标签: python if-statement python-3.x iteration


    【解决方案1】:

    不完全确定你想要什么,但我认为就是这样:

    if os.path.isdir(os.path.join(directory, subdir)) and subdir.lower() in [i['names'] for i in testnames.values()]
    

    【讨论】:

    • 感谢 pzp,它似乎没有返回任何结果,我已经修改了我的帖子,希望它能澄清。
    【解决方案2】:

    这个怎么样?

    testn1 = {'names':('tn1_name1','tn1_name2','tn1_name3'),'exts':('.log','.txt')}
    testn2 = {'names':('tn2_name1'),'exts':('.nfo')}
    testnames = {1:testn1,2:testn1}
    
    directory = 'C:\\temp\\root\\'
    
    for dirname, _, filenames in os.walk(directory):
        the_dir =  os.path.split(dirname)[-1]
        for testn in testnames.itervalues():
            if the_dir in testn['names']:
                for file in filenames:
                    _, ext = os.path.splitext(file)
                    if ext in testn['exts']:
                        print the_dir, file
    

    【讨论】:

    • 有一些错误,但我现在已经对其进行了测试......虽然不确定你到底想要做什么
    • 嗨朱利安,还没有走这条路,我想看看我是否可以先简单地调整那条线。如果其他所有方法都失败了,将重新进行。谢谢
    【解决方案3】:

    做到了!

    if os.path.isdir(os.path.join(directory, subdir)) and [i for i in testnames.values() if subdir.lower() in i['names']]:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2012-03-12
      • 2019-05-25
      • 2023-04-07
      • 2018-07-11
      • 2016-07-23
      • 2019-10-13
      相关资源
      最近更新 更多