繁体   English   中英

字典中具有多个值的单个键

[英]single key with multiple values in a dict

我的代码中可以包含一个全局字典吗,如下所示:

group = { 
        'vowel' : ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'],
        'consonant' : ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh']
        } 

它具有一个键和多个值。 我需要这个指示,因为我必须确保音素是元音或辅音,才能在代码中继续进行。 稍后在代码中,我必须做类似的事情,

if phoneme == vowel :
    do this
else :
    do that (for consonants)     

谢谢。

使用集合更有效(如果需要,可以将它们按字典分组):

vowels = set(['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'])
consonants = set(['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh'])


if phoneme in vowels:
    do this
else :
    do that (for consonants)

是的,您可以这样做,但是使用它的代码应该看起来像这样:

if phoneme in group["vowel"]:
    # ...

就是说,您可能要考虑使用set()而不是列表来为您提供更快的查找,即

group = { 
        'vowel' : set(('aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o')),
        'consonant' : set(('b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh')),
} 

您可以使用操作作为值来创建“反向”字典:

import operator as op

group = { 
        'vowel' : ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'],
        'consonant' : ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh']
        } 

# define methods functionVowel and functionConsonant

action = {'vowel': lambda x: op.methodcaller(functionVowel, x),
          'consonant': lambda x: op.methodcaller(functionConsonant, x)}

action_phoneme = dict((char, action[k]) for k,v in group.iteritems() for phoneme in v)

然后直接致电给他们:

action_phoneme[phoneme]()

是的,但是您的代码将类似于:

if phoneme in group['vowel'] :
    do this
else :
    do that (for consonants)     

您应该使用列表而不是字典。

vowel = ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o']
consonant = ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh']

因此,您可以确定:

if phoneme is in vowel:
    do this
else:
    do that

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM