简体   繁体   中英

Can I produce two sums from a single python dictionary comprehension based on matching the keys with two mutually exclusive key lists?

I am trying to output the sum of consonant and vowel values from a dictionary containing letter_number_pairs as shown below:

vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}

The question I'm wondering is: "Can I sum the vowel values and sum the consonant values in a single pass?" That is, can I avoid executing two passes of the dictionary as shown in my working example below:

vowel_value_sum     = sum(value for (letter, value) in letter_number_pairs.items() if letter in vowels)
consonant_value_sum = sum(value for (letter, value) in letter_number_pairs.items() if letter in consonants)

Yes, this is possible in a single pass.

Note the inner set inclusion checks are O(1).

a, b = 0, 0

vowels = set(vowels)

for k, v in letter_number_pairs.items():
    if k in vowels:
        a += v
    else:
        b += v

print([a, b])

# [12, 41]

Simply restructure your vowels and consonants data:

letters = {'vowels':['a','e','i','o','u'], 'consonants':['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']}
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}
final_sums = {a:sum(letter_number_pairs.get(i, 0) for i in b) for a, b in letters.items()}

Output:

{'vowels': 12, 'consonants': 41}

If you want in one iteration then you can try this approach:

vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}

vowel_sum=[]
conso_sum =[]
for i in letter_number_pairs:
    if i in vowels:
        vowel_sum.append(letter_number_pairs[i])
    elif i in consonants:
        conso_sum.append(letter_number_pairs[i])
    else:
        pass    #in case of special characters


print(sum(vowel_sum))
print(sum(conso_sum))

output:

12
41

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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