Python 如果列表中的项与字典中子元素的列表中的项匹配
全新的蟒蛇和树桩都准备好了,将感谢一只手Python 如果列表中的项与字典中子元素的列表中的项匹配,python,if-statement,python-3.x,iteration,Python,If Statement,Python 3.x,Iteration,全新的蟒蛇和树桩都准备好了,将感谢一只手 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)
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上的headup,我不太确定您想要什么,但我想这就是它:
if os.path.isdir(os.path.join(directory, subdir)) and subdir.lower() in [i['names'] for i in testnames.values()]
这个怎么样
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
成功了
if os.path.isdir(os.path.join(directory, subdir)) and [i for i in testnames.values() if subdir.lower() in i['names']]:
有一些错误,但我现在已经测试过了。。。我不确定你到底想做什么Hi Julien,还没有走这条路,我想看看我能不能先简单地调整这一行。如果所有其他方法都失败,将重新开始。谢谢你,它似乎没有返回任何结果,我已经修改了我的帖子,希望它能澄清。