user1487178
user1487178

Reputation: 93

python checking presence of a list element

I am trying to solve a more generic problem similar to the following. In the following, I get vow_array, which indicates the presence of a subset of vowels in some text, say, sent to my program. I need to print each vowel's presence as 0 or 1.

ch_a = 0
ch_e = 0
ch_i = 0
ch_o = 0
ch_u = 0

# vow_array is generated at runtime; here is an example
vow_array = ['a', 'o', 'u']

if 'a' in vow_array:
    ch_a = ch_a + 1
if 'e' in vow_array:
    ch_e = ch_e + 1
if 'i' in vow_array:
    ch_i = ch_i + 1
if 'o' in vow_array:
    ch_o = ch_o + 1
if 'u' in vow_array:
    ch_u = ch_u + 1

print ch_a, ch_e, ch_i, ch_o, ch_u

I think this code is too long and prone to errors. Is there a more compact way of writing this? Also, say if I had to do this for all 'letters' in the alphabet I don't want to have to repeat the code.

Upvotes: 1

Views: 1631

Answers (3)

Blender
Blender

Reputation: 298076

Definitely.

If you ever have variables with the same prefix (ch_a, ch_e, ...), you need to use a dictionary or a list to group them:

vowels = {
    'a': 0,
    'e': 0,
    'i': 0,
    'o': 0,
    'u': 0
}

vowel_array = ['a', 'o', 'u']

for vowel in vowels.keys():
    if vowel in vowel_array:
        vowels[vowel] += 1

print vowels

A more Pythonic solution would be something like this:

>>> from collections import Counter
>>>
>>> letters = 'i am a sentence'
>>> Counter(letters)
Counter({' ': 3, 'e': 3, 'a': 2, 'n': 2, 'c': 1, 'i': 1, 'm': 1, 's': 1, 't': 1})

Upvotes: 6

RocketDonkey
RocketDonkey

Reputation: 37249

Same idea as @Blender's, just with a different way of initializing the dictionary (you can do this with a dict comprehension in Python >2.7):

>>> vowels = dict((v, 0) for v in 'aeiou')
>>> vow_array = ['a', 'o', 'u']
>>> for vow in vow_array:
...   vowels[vow] += 1
>>> vowels
{'e': 0, 'i': 0, 'o': 1, 'u': 1, 'a': 1}

And if sorting it is a concern:

>>> for value in sorted(vowels):
...   print '{0}: {1}'.format(value, vowels[value])
...
a: 1
e: 0
i: 0
o: 1
u: 1

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25695

try this:

ch_dict = {'a':0,'e':0,'i':0,'o':0,'u':0}
vow_array = ['a','o','u']
for d in vow_array:
   ch_dict[d] = ch_dict[d] + 1

print(ch_dict)

Upvotes: 0

Related Questions