Translation: practical Python Programming 02_ 02_ Containers

codists 2021-02-22 13:10:42
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).

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

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

  1. Python中的解决中文字符编码的问题
  2. Solving the problem of Chinese character coding in Python
  3. Translation: practical Python Programming 02_ 01_ Datatypes
  4. Installation and use of Python and tensorflow in win10 environment (Python version 3.6, tensorflow version 1.6)
  5. Python series 46
  6. Linux安装Python3
  7. 【python接口自动化】- 正则用例参数化
  8. Python RestFul Api 设计
  9. filecmp --- 文件及目录的比较│Python标准库
  10. Installing python3 on Linux
  11. [Python] Matplotlib 圖表的繪製和美化技巧
  12. (資料科學學習手札108)Python+Dash快速web應用開發——靜態部件篇(上)
  13. 翻譯:《實用的Python程式設計》02_01_Datatypes
  14. 【python接口自动化】- 正则用例参数化
  15. 翻译:《实用的Python编程》02_02_Containers
  16. 两年Java,去字节跳动写Python和Go
  17. [Python interface automation] - regular use case parameterization
  18. Python restful API design
  19. 翻译:《实用的Python编程》02_02_Containers
  20. 两年Java,去字节跳动写Python和Go
  21. 翻译:《实用的Python编程》02_02_Containers
  22. Python基于粒子群优化的投资组合优化研究
  23. ubuntu部署django项目
  24. 兩年Java,去位元組跳動寫Python和Go
  25. 翻譯:《實用的Python程式設計》02_02_Containers
  26. 这样学习Python,爷爷都学会了!超简单Python入门
  27. [Python] 基于 jieba 的中文分词总结
  28. 【python】递归听了N次也没印象,读完这篇你就懂了
  29. [Python] 基于 jieba 的中文分词总结
  30. 人理解迭代,神则体会递归,从电影艺术到Python代码实现神的逆向思维模式
  31. [Python] 基於 jieba 的中文分詞總結
  32. Python属于后端开发还是前端开发?Python入门!
  33. 【python】递归听了N次也没印象,读完这篇你就懂了
  34. 一天快速入门python
  35. 学习Python对年龄有没有要求?30岁可以吗?
  36. 清华教授!12小时整理的最全Python教程(文末无偿分享)
  37. 使用Python开发DeFi项目
  38. python 函数详解
  39. Python工程师是做什么的?前景如何?
  40. Filecmp -- comparison of files and directories
  41. Python - zip() 函数
  42. 30 周年生日,Python 先驱是怎么评价这门语言的?
  43. Drawing and beautifying skills of [Python] Matplotlib chart
  44. Python + dash rapid web application development static components
  45. Translation: practical Python Programming 02_ 01_ Datatypes
  46. python将excel自适应导入数据库
  47. 从小白到大师,这里有一份Pandas入门指南
  48. [Python] 茎叶图和复合饼图的画法
  49. [Python interface automation] - regular use case parameterization
  50. Translation: practical Python Programming 02_ 02_ Containers
  51. Two years of Java, to write Python and go
  52. Translation: practical Python Programming 02_ 02_ Containers
  53. Two years of Java, to write Python and go
  54. Python-geoplot 空间核密度估计图绘制
  55. Python-seaborn 经济学人经典图表仿制
  56. python空间绘图- regionmask掩膜操作示例
  57. Python 空间绘图 - Cartopy 经纬度添加
  58. Python-pykrige包-克里金(Kriging)插值计算及可视化绘制
  59. Python 批量重采样、掩膜、坡度提取
  60. python - 多种交通方式可达圈分析