如何使用列表推导同时检查字典中的不同值键

时间:2012-03-28 13:24:05

标签: python dictionary list-comprehension

我正在努力完成一项任务,但遇到了一些困难。有人可以直截了当地说明以下事项:

#This worked for me
myFormats = {'audio': ('.wav', '.wma', '.mp3'), 'video': ('.mpg', '.mp4', '.mpeg')}

myFile = '5DeadlyVenoms.mp3'
f_exten = (x for x in myFormats['audio'] + myFormats['video'] if myFile.endswith(x))
extension = f_exten.next()

使用以下内容导致此错误:

myFormats = {'audio': {'.wav', '.wma', '.mp3'}, 'video': {'.avi', '.mpg', '.mp4', '.mpeg'}}

回溯:

Traceback (most recent call last):
File "C:\Users\GVRSQA004\Desktop\udCombo.py", line 65, in fileFormats
f_exten = (x for x in myFormats['audio'] + myFormats['video'] if myFile.endswith(x))
TypeError: unsupported operand type(s) for +: 'set' and 'set'
Traceback (most recent call last):
File "C:\Users\GVRSQA004\Desktop\udCombo.py", line 65, in fileFormats
f_exten = (x for x in myFormats['audio'] + myFormats['video'] if myFile.endswith(x))
TypeError: unsupported operand type(s) for +: 'set' and 'set'

3 个答案:

答案 0 :(得分:2)

这是你的错误:

myFormats['audio'] or myFormats['video']

这将始终只返回myFormats['audio'],因为这是一个逻辑or。你想要的是附加的两个元组:

myFormats['audio'] + myFormats['video']

更好的解决方案是使用set和生成器:

formats = {'audio': {'.wav', '.wma', '.mp3'}, 'video': {'.mpg', '.mp4', '.mpeg'}}

myfile = '5DeadlyVenoms.mp3'
extensions = (x for x in formats['audio'] + formats['video'] if myfile.endswith(x))
extension = extensions.next()

答案 1 :(得分:1)

[x for v in myFormats.itervalues() for x in v if myFile.endswith(x)]

返回

['.mp3']

这是你想要的吗?

答案 2 :(得分:1)

您真的想要一个包含所有匹配文件扩展名的列表吗?看起来你只是在使用第一个。

如果不是:

>>> myFormats = {'audio': {'.wav', '.wma', '.mp3'}, 'video': {'.mpg', '.mp4', '.mpeg'}}
>>>
>>> myFile = '5DeadlyVenoms.mp3'
...
>>> def get_extension(file_name, formats):
...     for key, extensions in formats.items():
...         for extension in extensions:
...             if file_name.endswith(extension):
...                 return extension
...
>>> myFile_extension = get_extension(myFile, myFormats)
>>> myFile_extension
'.mp3'

这将允许您轻松修改它以在需要时返回密钥(即音频或视频),或者如果您需要多个扩展,则将其转换为生成器。