Jon
Jon

Reputation: 1801

Pythonic way to write for loops with nested if statements

Lets say I had a simple python list that contained the type of expense and I wanted to iterate over these expenses with a for loop. At each iteration, if the indice produces the correct expense type a counter will be advanced by 1. I can easily write this with the code below, but it is not using a fast running for loop.

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
sum = 0
for i in range(len(array)):
    if array[i] == 'Groceries':
        sum += 1 

Is there a more pythonic way to write this loop that accelerates the execution? I have seen examples that would look something like the code snippet below. NOTE: The code snippet below does not work, it is just an example of an accelerated format that I have seen before, but do not fully understand.

sum = [sum + 1 for i in array if array[i] == 'Groceries']

Upvotes: 1

Views: 605

Answers (3)

Artur Barseghyan
Artur Barseghyan

Reputation: 14172

If it's just about counts, try collections.Counter:

from collections import Counter


array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']

counts = Counter(array)

print(counts)
# Counter({'Groceries': 2, 'Bills': 1, 'Restaurant': 1, 'Misc': 1})

print(counts['Groceries'])
# 2

Upvotes: 2

BoarGules
BoarGules

Reputation: 16942

You seem to think you need a list comprehension for this. But list comprehensions produce lists, and you want a scalar. Try array. count("Groceries").

Upvotes: 1

Alp
Alp

Reputation: 3105

for i in range(len(array)):

is definitely NOT the Python-ic way of iterating over an array. It is VisualBasic thinking, from which you should free yourself.

If you want to iterate over an array, just iterate over it as follows:

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
for eachItem in array:
   ...

What you do in the loop is up to you. If you want to count howmany groceries in the list, then you can do this:

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
groceriesTotal = 0
for eachItem in array:
    if eachItem == 'Groceries':
         groceriesTotal = groceriesTotal + 1

This is simple, clear and pythonic enough to be readable by others.

Upvotes: 1

Related Questions