Translation: practical Python Programming 02_ 02_ Containers

codists 2021-02-22 13:00:19
translation practical python programming 02_


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).

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

版权声明
本文为[codists]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210221130425444X.html

  1. Python 3 entry, see this is enough
  2. 华为大佬打造的400集Python视频学起来,学完万物皆可爬
  3. 400 episodes of Python video created by Huawei boss
  4. django之csrf_exempt解决跨域请求的问题
  5. CSRF of Django_ Exempt solves the problem of cross domain requests
  6. 1.7 万 Star!一个简单实用的 Python 进度条库
  7. 17000 stars! A simple and practical Python progress bar library
  8. Python爬虫:设置Cookie解决网站拦截并爬取蚂蚁短租
  9. Python crawler: setting cookie to solve website interception and crawling ant short rent
  10. Python-Net编程
  11. Python net programming
  12. 学习Python数学英语基础重要吗?Python教程!
  13. Is it important to learn the basics of math and English in Python!
  14. Python数据分析常用库有哪些?Python学习!
  15. What are the common libraries for Python data analysis? Learn Python!
  16. win 创建python虚拟环境
  17. Creating Python virtual environment with win
  18. In order to automatically collect B station barrage, I developed a tool in Python
  19. 用Python编程语言来实现阿姆斯特朗数的检查
  20. Using python programming language to check Armstrong number
  21. Python中的解决中文字符编码的问题
  22. Solving the problem of Chinese character coding in Python
  23. Translation: practical Python Programming 02_ 01_ Datatypes
  24. Installation and use of Python and tensorflow in win10 environment (Python version 3.6, tensorflow version 1.6)
  25. Python series 46
  26. Linux安装Python3
  27. 【python接口自动化】- 正则用例参数化
  28. Python RestFul Api 设计
  29. filecmp --- 文件及目录的比较│Python标准库
  30. Installing python3 on Linux
  31. [Python] Matplotlib 圖表的繪製和美化技巧
  32. (資料科學學習手札108)Python+Dash快速web應用開發——靜態部件篇(上)
  33. 翻譯:《實用的Python程式設計》02_01_Datatypes
  34. 【python接口自动化】- 正则用例参数化
  35. 翻译:《实用的Python编程》02_02_Containers
  36. 两年Java,去字节跳动写Python和Go
  37. [Python interface automation] - regular use case parameterization
  38. Python restful API design
  39. 翻译:《实用的Python编程》02_02_Containers
  40. 两年Java,去字节跳动写Python和Go
  41. 翻译:《实用的Python编程》02_02_Containers
  42. Python基于粒子群优化的投资组合优化研究
  43. ubuntu部署django项目
  44. 兩年Java,去位元組跳動寫Python和Go
  45. 翻譯:《實用的Python程式設計》02_02_Containers
  46. 这样学习Python,爷爷都学会了!超简单Python入门
  47. [Python] 基于 jieba 的中文分词总结
  48. 【python】递归听了N次也没印象,读完这篇你就懂了
  49. [Python] 基于 jieba 的中文分词总结
  50. 人理解迭代,神则体会递归,从电影艺术到Python代码实现神的逆向思维模式
  51. [Python] 基於 jieba 的中文分詞總結
  52. Python属于后端开发还是前端开发?Python入门!
  53. 【python】递归听了N次也没印象,读完这篇你就懂了
  54. 一天快速入门python
  55. 学习Python对年龄有没有要求?30岁可以吗?
  56. 清华教授!12小时整理的最全Python教程(文末无偿分享)
  57. Filecmp -- comparison of files and directories
  58. Drawing and beautifying skills of [Python] Matplotlib chart
  59. Python + dash rapid web application development static components
  60. Translation: practical Python Programming 02_ 01_ Datatypes