Translation: practical Python Programming 02_ 02_ Containers

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


[ Catalog ](https://github.com/codists/practical-python-zh/blob/main/Notes/Contents.md) \| [ Last section (2.1 Data type )](https://www.cnblogs.com/codists/p/14423547.html) \| [ Next section (2.3 format )]()# 2.2 Containers this section discusses lists (list), Dictionaries (dict) And collection (set).### General , Programs have to deal with many objects .* A portfolio of stocks * There are three main options for the stock price list ( Translation notes : Data structure ) have access to :* list . The order of the data .* Dictionaries . Unordered data .* aggregate . Different and disordered data .### Think of lists as containers when data order is important , Please use the list . Remember , Lists can store objects of any type . for example , A list of tuples :```pythonportfolio = [ ('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 builds lists from scratch .```pythonrecords = [] # Initial empty list# Use .append() to add more itemsrecords.append(('GOOG', 100, 490.10))records.append(('IBM', 50, 91.3))...``` An example of reading records from a file :```pythonrecords = [] # Initial empty listwith 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])))```### Think of the dictionary as a container if you want to query randomly and quickly ( By key name ), So dictionaries are very useful . for example , A dictionary of stock prices :```pythonprices = { 'GOOG': 513.25, 'CAT': 87.22, 'IBM': 93.37, 'MSFT': 44.12}``` Here are some simple queries :```python>>> prices['IBM']93.37>>> prices['GOOG']513.25>>>```### Dictionary building an example of building a dictionary from scratch :```pythonprices = {} # Initial empty dict# Insert new itemsprices['GOOG'] = 513.25prices['CAT'] = 87.22prices['IBM'] = 93.37``` Examples of filling dictionaries from file content :```pythonprices = {} # Initial empty dictwith 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 . We need to find some ways to modify the code to solve this problem ( See exercise 2.6).### Dictionary query test key exists :```pythonif key in d: # YESelse: # NO``` You can query for values that may not exist , And provide a default value if the value does not exist .```pythonname = d.get(key, default)``` Example :```python>>> prices.get('IBM', 0.0)93.37>>> prices.get('SCOX', 0.0)0.0>>>```### The key combination is in Python in , Almost any type of value can be used as a dictionary key . The key of a dictionary must be immutable . for example , Tuple :```pythonholidays = { (1, 1) : 'New Years', (3, 14) : 'Pi day', (9, 13) : "Programmer's day",}``` Then visit :```python>>> 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 ) It's variable .*### A set is different and disordered data .```pythontech_stocks = { 'IBM','AAPL','MSFT' }# Alternative syntaxtech_stocks = set(['IBM', 'AAPL', 'MSFT'])``` Collections are useful for membership testing .```python>>> tech_stocksset(['AAPL', 'IBM', 'MSFT'])>>> 'IBM' in tech_stocksTrue>>> 'FB' in tech_stocksFalse>>>``` Collections are also useful for de duplication .```pythonnames = ['IBM', 'AAPL', 'GOOG', 'IBM', 'GOOG', 'YHOO']unique = set(names)# unique = set(['IBM', 'AAPL','GOOG','YHOO'])``` Other set operations :```pythonnames.add('CAT') # Add an itemnames.remove('YHOO') # Remove an items1 | s2 # Set unions1 & s2 # Set intersections1 - s2 # Set difference```## Practice in these exercises , The program you started building is one of the main programs used in the rest of this course . Please visit `Work/report.py` Work in the archives .### Practice 2.4: A list of tuples `Data/portfolio.csv` The file contains a list of stocks in the portfolio . stay [ Practice 1.30](../01_Introduction/07_Functions.md) in , You write a program that reads the file and performs simple calculations `portfolio_cost(filename)` Function . The code should look like this :```python# pcost.pyimport csvdef 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``` Use this code as a guide , Create a new file `report.py` . stay `report.py` In Archives , Define `read_portfolio(filename)` Function , This function opens `Data/portfolio.csv` File and read it into a list containing tuples . Therefore , You need to make some minor changes to the code above . First , Create a variable that is initially set to an empty list , Instead of defining `total_cost = 0`. for example :```pythonportfolio = []``` Then , 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 .```pythonfor row in rows: holding = (row[0], int(row[1]), float(row[2])) portfolio.append(holding)``` Finally , Return what you get `portfolio` list . Please test the function interactively ( remind , To do this , First of all, it needs to be executed in the interpreter `report.py` The program ).* Tips : When executing files on the terminal , Please use `-i` Arguments .*```python>>> 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>>>``` Creating a list of tuples is very similar to two-dimensional (2-D) Array . for example , Use such as `portfolio[row][column]` ( `row` and `column` It's an integer ) Query to access specific columns and rows . That is to say , You can rewrite the last... With a statement like this for Turn around :```python>>> total = 0.0>>> for name, shares, price in portfolio: total += shares*price>>> print(total)44671.15>>>```### Practice 2.5: Contains a list of dictionaries using dictionaries ( Instead of 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 . ```python>>> 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... Here , The different fields of each entry are accessed by key names , Instead of the column number of a numeric type . This is usually the preferred way , Because the code is easy to read later . Looking at large dictionaries or lists can be confusing . To clean up the output of debugging , Consider using `pprint()` Function .```python>>> 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: Think of dictionaries as containers where you use indexes instead of numbers to query an element , Dictionaries are a useful way to track elements . stay Python shell in , Try using a dictionary :```python>>> 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 pricesFalse>>>``` The `Data/prices.csv` The file contains a series of lines with stock prices , It looks like this :```csv"AA",9.22"AXP",24.85"BA",44.85"BAC",11.27"C",3.72...``` Write `read_prices(filename)` Function reads a set of prices like this into a dictionary , The key in the dictionary represents the name of the stock , The dictionary value represents the price of the stock . Therefore , Start with an empty dictionary , And start inserting values like above . however , Now reading values from the file . We will use this data structure to quickly query the price of a given stock name . This part needs a few tricks . First , Make sure to use as before `csv` Module —— There's no need to reinvent the wheel here .```python>>> 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 . Note that the last line of the above data is an empty list —— It means there's no information in 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 prevent errors in the data will be better ? Finished writing `read_prices()` Function , Test it interactively and make sure it works :```python>>> prices = read_prices('Data/prices.csv')>>> prices['IBM']106.28>>> prices['MSFT']20.89>>>```### Practice 2.7: See if you can retire by adding some statements to calculate the profit and loss `report.py` The program , Bring all the work together . These sentences should be used in practice 2.5 Store a list of stock names in , And practicing 2.6 A dictionary that stores stock prices in , And calculate the current value of the portfolio and the profit and loss .[ Catalog ](https://github.com/codists/practical-python-zh/blob/main/Notes/Contents.md) \| [ Last section (2.1 Data type )](https://www.cnblogs.com/codists/p/14423547.html) \| [ Next section (2.3 format )]() notes : See... For the complete translation [https://github.com/codists/practical-python-zh](https://github.com/codists/practical-py
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210221170946474x.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 - 多种交通方式可达圈分析