Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 2.59 KB

File metadata and controls

93 lines (71 loc) · 2.59 KB

Appendix A: Advanced Ideas

We’re going to look at a few "modern" ways of handling a collection of data. Frequently, you have a list, or an array, of data that needs to be gone through to print it out, transform it in some way, or to summarize it (such as a total or an average). As you have seen in the code patterns section, there are common loops used for such things, a simple pattern that you can memorize.

There are other method-functions of doing these things, and we’re going to discuss a few of them here. These ideas are based primarily on method-functions made popular by Hadoop and other "big data" applications and tools. And what’s good for "big" data is often good for "small" data as well.

Each of these sections is an example of a more "elegant" way of expressing coding logic. By studying each one and comparing it to the ways we’ve discussed before using loops and conditional statements, we’re expanding your understanding, making you see how these techniques can be used to create more extensible and elegant code.

Let’s use this array for the following examples.

groceries = [
  {
    'name': 'Breakfast Cereal',
    'price': 5.50,
  },
  {
    'name': 'Rice',
    'price': 14.99,
  },
  {
    'name': 'Oranges',
    'price': 6.49,
  },
  {
    'name': 'Crackers',
    'price': 4.79,
  },
  {
    'name': 'Potatoes',
    'price': 3.99,
  },
]

A common grocery list, we have this as a list of dictionaries (what’s known as a key/value data structure). The dictionaries hold a grocery item, its name and its price.

Simplifying Loops

Now, if you wanted to print out each item’s name in the grocery list to the console, you could do something like this:

for item in groceries:
    print(item['name'])

This is a very common code pattern in Python. It’s also a pretty simple loop.

Rather, how about this:

[print(item['name']) for item in groceries]

It is list comprehension, and in Python its remarkably powerful. Say we wanted to print the total cost of our grocery list. If we did it with a loop and sum variable:

prices = []
for item in groceries:
    prices.append(item['price'])

sump = 0
for price in prices:
    sum = sum + price

print(p)

Not too bad, but we can put it all on one line, and only one loop:

total = sum([item['price'] for item in groceries])

# printing total gets us 35.76

This example step through the grocery list, pulling out each item, and the item['price'] pulls out the price and places it in a list. When loop is done, the sum() function sums and returns all the prices in the list.