Catalog | Previous section (2.1 data type ) | Next section (2.3 format )

2.2 Containers

This section discusses lists (list), Dictionaries (dict) And collection (set).

summary

Usually , Programs have to deal with many objects .

  • A portfolio of stocks
  • Stock price list

There are three main options ( Translation notes : data structure ) have access to :

  • list . Ordered data .
  • Dictionaries . Unordered data .
  • aggregate . Different and unordered data .

Think of the list as a container

When data order is important , Please use the list . remember , Lists can store any type of object . for example , A list of tuples :

portfolio = [
('GOOG', 100, 490.1),
('IBM', 50, 91.3),
('CAT', 150, 83.44)
] portfolio[0] # ('GOOG', 100, 490.1)
portfolio[2] # ('CAT', 150, 83.44)

List building

Building lists from scratch .

records = [] # Initial empty list
# Use .append() to add more items
records.append(('GOOG', 100, 490.10))
records.append(('IBM', 50, 91.3))
...

Example of reading records from a file :

records = [] # Initial empty list
with open('Data/portfolio.csv', 'rt') as f:
next(f) # Skip header
for line in f:
row = line.split(',')
records.append((row[0], int(row[1]), float(row[2])))

Use dictionaries as containers

If you want to do a quick random search ( By key name ), So dictionaries are useful . for example , A dictionary of stock prices :

prices = {
'GOOG': 513.25,
'CAT': 87.22,
'IBM': 93.37,
'MSFT': 44.12
}

Here are some simple searches :

>>> prices['IBM']
93.37
>>> prices['GOOG']
513.25
>>>

Dictionary building

An example of building a dictionary from scratch :

prices = {} # Initial empty dict
# Insert new items
prices['GOOG'] = 513.25
prices['CAT'] = 87.22
prices['IBM'] = 93.37

An example of filling a dictionary from the contents of a file :

prices = {} # Initial empty dict
with open('Data/prices.csv', 'rt') as f:
for line in f:
row = line.split(',')
prices[row[0]] = float(row[1])

Be careful : If it's in Data/prices.csv Try this operation on the file , You'll find that it's almost working —— however , There is a blank line at the end that causes the program to crash . Some ways need to be found to modify the code to solve this problem ( See exercise 2.6).

Dictionary search

Test whether the key exists :

if key in d:
# YES
else:
# NO

You can find values that may not exist , And provide a default value if the value does not exist .

name = d.get(key, default)

Example :

>>> prices.get('IBM', 0.0)
93.37
>>> prices.get('SCOX', 0.0)
0.0
>>>

Composite key

stay Python in , Almost any type of value can be used as a dictionary key . The key of a dictionary must be an immutable type . for example , Tuples :

holidays = {
(1, 1) : 'New Years',
(3, 14) : 'Pi day',
(9, 13) : "Programmer's day",
}

And then visit :

>>> holidays[3, 14]
'Pi day'
>>>

list , A set or any other dictionary can't be used as a dictionary key , Because lists and dictionaries ( Translation notes : Collections are also implemented using hash technology ) Is variable .

aggregate

Sets are different and unordered data .

tech_stocks = { 'IBM','AAPL','MSFT' }
# Alternative syntax
tech_stocks = set(['IBM', 'AAPL', 'MSFT'])

Collections are useful for membership testing .

>>> tech_stocks
set(['AAPL', 'IBM', 'MSFT'])
>>> 'IBM' in tech_stocks
True
>>> 'FB' in tech_stocks
False
>>>

Collections are also useful for de duplication .

names = ['IBM', 'AAPL', 'GOOG', 'IBM', 'GOOG', 'YHOO']
unique = set(names)
# unique = set(['IBM', 'AAPL','GOOG','YHOO'])

Other set operations :

names.add('CAT') # Add an item
names.remove('YHOO') # Remove an item s1 | s2 # Set union
s1 & s2 # Set intersection
s1 - s2 # Set difference

practice

In these exercises , The program you started building is one of the main programs used for the rest of the course . Please be there. Work/report.py Working in documents .

practice 2.4: A list of tuples

Data/portfolio.csv The file contains a list of stocks in the portfolio . stay practice 1.30 in , You write a program that reads the file and performs simple calculations portfolio_cost(filename) function .

The code should look like this :

# pcost.py
import csv
def portfolio_cost(filename):
'''Computes the total cost (shares*price) of a portfolio file'''
total_cost = 0.0 with open(filename, 'rt') as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
nshares = int(row[1])
price = float(row[2])
total_cost += nshares * price
return total_cost

Please use these codes as a guide , Create a new file report.py . stay report.py In file , Definition read_portfolio(filename) function , This function opens Data/portfolio.csv File and read it into a list containing tuples . So , You need to make some minor changes to the code above .

First , Create a variable that is initially set to an empty list , Not the definition total_cost = 0. for example :

portfolio = []

next , Store each row exactly in the tuple ( As you did in the last exercise ), Then append the tuple to the list , Instead of adding up the total cost .

for row in rows:
holding = (row[0], int(row[1]), float(row[2]))
portfolio.append(holding)

Last , Return what you get portfolio list .

Please test the function interactively ( remind , To do this , First you need to run in the interpreter report.py Program ).

Tips : When executing files on the terminal , Please use -i Parameters .

>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> portfolio
[('AA', 100, 32.2), ('IBM', 50, 91.1), ('CAT', 150, 83.44), ('MSFT', 200, 51.23),
('GE', 95, 40.37), ('MSFT', 50, 65.1), ('IBM', 100, 70.44)]
>>>
>>> portfolio[0]
('AA', 100, 32.2)
>>> portfolio[1]
('IBM', 50, 91.1)
>>> portfolio[1][1]
50
>>> total = 0.0
>>> for s in portfolio:
total += s[1] * s[2] >>> print(total)
44671.15
>>>

The list of tuples created is very similar to 2D (2-D) Array . for example , Use things like portfolio[row][column]row and column Is an integer ) To access specific columns and rows .

in other words , You can rewrite the last... With a statement like this for loop :

>>> total = 0.0
>>> for name, shares, price in portfolio:
total += shares*price >>> print(total)
44671.15
>>>

practice 2.5: A list of dictionaries

Using dictionaries ( Not tuples ) I'm practicing 2.4 To represent stocks in a portfolio . In the dictionary , Use the field name "name", "shares" and "price" To represent different columns in the input file .

With practice 2.4 Test this new function in the same way as in .

>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> portfolio
[{'name': 'AA', 'shares': 100, 'price': 32.2}, {'name': 'IBM', 'shares': 50, 'price': 91.1},
{'name': 'CAT', 'shares': 150, 'price': 83.44}, {'name': 'MSFT', 'shares': 200, 'price': 51.23},
{'name': 'GE', 'shares': 95, 'price': 40.37}, {'name': 'MSFT', 'shares': 50, 'price': 65.1},
{'name': 'IBM', 'shares': 100, 'price': 70.44}]
>>> portfolio[0]
{'name': 'AA', 'shares': 100, 'price': 32.2}
>>> portfolio[1]
{'name': 'IBM', 'shares': 50, 'price': 91.1}
>>> portfolio[1]['shares']
50
>>> total = 0.0
>>> for s in portfolio:
total += s['shares']*s['price'] >>> print(total)
44671.15
>>>

You can see it here , The different fields of each entry are accessed by key names , Instead of the column number of the numeric type . This is usually the preferred way , Because the resulting code is easy to read later .

Looking at large dictionaries or lists can be confusing . To clean up the debug output , Consider using pprint() function .

>>> from pprint import pprint
>>> pprint(portfolio)
[{'name': 'AA', 'price': 32.2, 'shares': 100},
{'name': 'IBM', 'price': 91.1, 'shares': 50},
{'name': 'CAT', 'price': 83.44, 'shares': 150},
{'name': 'MSFT', 'price': 51.23, 'shares': 200},
{'name': 'GE', 'price': 40.37, 'shares': 95},
{'name': 'MSFT', 'price': 65.1, 'shares': 50},
{'name': 'IBM', 'price': 70.44, 'shares': 100}]
>>>

practice 2.6: Use dictionaries as containers

Where an index is used instead of a number to find an element , Dictionaries are a useful way to track elements . stay Python shell in , Try using a dictionary :

>>> prices = { }
>>> prices['IBM'] = 92.45
>>> prices['MSFT'] = 45.12
>>> prices
... look at the result ...
>>> prices['IBM']
92.45
>>> prices['AAPL']
... look at the result ...
>>> 'AAPL' in prices
False
>>>

The Data/prices.csv The file contains a series of lines with stock prices , Looks like this :

"AA",9.22
"AXP",24.85
"BA",44.85
"BAC",11.27
"C",3.72
...

To write read_prices(filename) Function to read a set of such prices into the dictionary , The key in the dictionary represents the name of the stock , The dictionary value represents the price of the stock .

So , Start with an empty dictionary , And start inserting values like above . however , Now reading values from file .

We will use this data structure to quickly find the price of a given stock name .

This part needs a few tricks . First , Make sure to use as before csv modular —— There's no need to reinvent the wheel here .

>>> import csv
>>> f = open('Data/prices.csv', 'r')
>>> rows = csv.reader(f)
>>> for row in rows:
print(row) ['AA', '9.22']
['AXP', '24.85']
...
[]
>>>

Another little trouble is Data/prices.csv There may be some blank lines in the file . Notice that the last line of the data above is an empty list —— It means there's no data on that line .

This may cause your program to terminate due to an exception . Use as appropriate try and except Statement to catch these exceptions . reflection : Use if Statement to guard against erroneous data ?

written read_prices() function , Test it interactively and make sure it works :

>>> prices = read_prices('Data/prices.csv')
>>> prices['IBM']
106.28
>>> prices['MSFT']
20.89
>>>

practice 2.7: See if you can retire

Add some statements to calculate profit and loss report.py Program , Connect all the work together . These sentences should be used in practice 2.5 A list of stock names stored in , And practicing 2.6 A dictionary of stock prices in , And calculate the current value of the portfolio and the profit and loss .

Catalog | Previous section (2.1 data type ) | Next section (2.3 format )

notes : See... For the complete translation https://github.com/codists/practical-python-zh

translate :《 Economic Python Programming 》02_02_Containers More articles about

  1. translate "Python Programming without a teacher —— The development of professional programmers "

    This book is in Sell well Python Programming class introductory book , Amazon, USA Kindle Programming class ranking one . Start learning python, There are also many books , I don't want to spend money in vain ( Buy it and put it there ), Look at an original English document , Prepare to translate a little every day , Put it in b ...

  2. Python Black hat programming 2.1 Python Programming Philosophy

    Python Black hat programming 2.1  Python Programming Philosophy The content of this section is somewhat interesting , It's about why a lot of people choose Python, Why do you like this language . I'll take you to worship Python The author's Python zen , And then let's get to know P ...

  3. Python Programming specification ----- Reprint

    Python Programming specification and performance optimization Ptyhon Programming specification code be-all Python Script files should be marked with # -*- coding:utf-8 -*- . Settings editor , Save as by default utf-8 Format . ...

  4. Study Python programming 11 It's an excellent resource

    This paper is written by   Bole Online  - atupal  Translated from  Alex Ivanovs. Welcome to the technical translation group . Please refer to the requirements at the end of the article for reprint . use Python It's not hard to write code , in fact , It has always been claimed to be the easiest programming to learn ...

  5. About Python Some questions and answers about programming

    About Python Some questions and answers about programming Introduction about 1 Months ago ,oschina.net And Huazhang books did an activity together :OSC The first 51 Q & A of experts in the period -- Chat python Those things , To promote the book I'm involved in < Write quality code : ...

  6. python Classic secretary must read :Python Programming fast Automate tedious work

    Website classification : Download resources > python e-book author : Panda burning incense link :http://www.pythonheidong.com/blog/article/69/ source :python Black hole network , focus ...

  7. CS231n Course notes translation 1:Python Numpy course

    translator's note : In this paper, the intelligent unit is launched , Translated from Stanford CS231n Course notes Python Numpy Tutorial, By the course teacher Andrej Karpathy Authorized to translate . This course is translated by Duke ,Flood Sung ...

  8. Study Python programming 19 A resource ( turn )

    Study Python programming 19 A resource 2018-01-07  The beauty of data and algorithms compile :wzhvictor, english :codecondo segmentfault.com/a/119000000418731 ...

  9. Python Learning manual of Python zen 、Python Programming specifications and function parameters

    In the last article , We introduced Python Examples of using regular expressions for , Now let's introduce Python zen . Python Programming specifications and function parameters . To view the previous article, please click :https://www.cnblogs.co ...

  10. Python Programming Notes binary 、 Character encoding 、 data type

    Python Programming Notes binary . Character encoding . data type One . Binary system bin() stay python Can be used in the bin() The built-in function gets the binary of a decimal number A unit of computer capacity 8bit = 1 bytes byte , The smallest memory ...

Random recommendation

  1. First time to know Linux—1

    1,Ctrl+C The function is to terminate the current command 2,ps Shows the program that is currently executing ( command )(process status) 3, Exit is exit, Press continuously exit, It will eventually shut down the terminal 4,Root It's the administrator , The other users are made up of ...

  2. Python Study two ( Generator and eight queens algorithm )

    I read about iterators and generators , General use is no problem , But I can't use it very often The classic eight queens problem is cited in the book , As a programmer, how can I miss the chance to do a problem , So I'll do it myself first , So there's this ugly Code for ...

  3. DbUtils Components

    DbUtils Components DbUtils Components , 1. simplify jdbc operation 2. Download components , introduce jar file : commons-dbutils-1.6.jar |-- DbUtils close resource . The load driver |-- ...

  4. remember NOIP Before the score comes out

    Baa ~ The results haven't come out yet ! But got everyone's program , There's also a bunch of folk data . I measured a lot of different data , Basically D1T1,D2T1,D2T2 All of them are solved by violence , No problem , The only thing is D1T2 Of link That question , When writing 2 ...

  5. c++ File read ( One )--- Input class uses and finds the current program path

    In view of the large turnover of personnel in the company , Design a small log locator , First read the log file With input and output stream class operation file than c Of stdio It's safer and easier , Of course, any such view is right, except for Daniel The first is to find the current file path , If you use GetCurrentD ...

  6. Launcher Knowledgeable demo, Mobile housekeeper's home and floating window

    Launcher Knowledgeable demo. It mainly imitates the effect of mobile phone housekeeper's house and floating window . It's simple . Post code directly Mainly used windowManager Update in updateViewLayout(view,params) ...

  7. ● Luogu P3168 [CQOI2015] Task query system

    Question chain : https://www.luogu.org/problemnew/show/P3168 Answer key : Chairman tree Forced Online ? Then we can directly build a line segment tree for each prefix time ( Persistent line tree ), The line segment tree maintains priority weights . ...

  8. div+css Basic course

    This article is saved as a reminder . Section 1   understand div+css One . What is? div+css div The element is html( Hypertext language ) An element in , Is the label , Used for html Big chunks in the document (block-level) Content provides structure and ...

  9. Bootstrap The font cannot be displayed

    Download the font The file is not in your project file .

  10. Android Of the four components broadcast The understanding of the

    Android Two types of broadcasting : 1. Static broadcast 2. Dynamic broadcasting Static registration broadcast : Manifeast Code block in : <receiver android:name=".broadcast.MyS ...