Translation: practical Python Programming 02_ 01_ Datatypes

codists 2021-02-20 22:10:51
translation practical python programming 02_


Catalog | Previous section (1.7 function ) | Next section (2.2 Containers )

2.1 Data types and data structures

This section introduces the data structure represented by tuples and dictionaries .

Raw data type

Python There are some raw data types :

  • Integers
  • Floating point numbers
  • character string ( Text )

Empty type

email_address = None

None Often used as a place holder for optional or missing values . It evaluates to... In a conditional statement False.

if email_address:
send_email(email_address, msg)

data structure

The actual program has more complex data . for example , Information about stock holdings :

100 shares of GOOG at $490.10

This is a three part “ object ”:

  • The name or symbol of a stock ("GOOG", character string )
  • Number of shares (100, Integers )
  • Price (490.10, Floating point numbers )

Tuples

A tuple is a collection of values grouped together .

Example :

s = ('GOOG', 100, 490.1)

Sometimes it's grammatically omitted () .

s = 'GOOG', 100, 490.1

A special case (0 Tuples ,1 Tuples ).

t = () # An empty tuple
w = ('GOOG', ) # A 1-item tuple

Tuples are generally used to represent simple records or structures .

Usually , It's a single object made up of multiple parts . There's a good analogy : Tuples are like a row in a database table .

The contents of tuples are ordered ( It's like an array ).

s = ('GOOG', 100, 490.1)
name = s[0] # 'GOOG'
shares = s[1] # 100
price = s[2] # 490.1

however , The contents of tuples cannot be modified .

>>> s[1] = 75
TypeError: object does not support item assignment

You can create a new metagroup based on the current tuple .

s = (s[0], 75, s[2])

Tuple packing

Tuples are more about packaging related items into an entity (entity) in .

s = ('GOOG', 100, 490.1)

then , The tuple is easily passed as a single object to the rest of the program .

Tuple unpacking

To use tuples elsewhere , You can unpack parts of a tuple into variables .

name, shares, price = s
print('Cost', shares * price)

The number of variables on the left must match the structure of the tuple .

name, shares = s # ERROR
Traceback (most recent call last):
...
ValueError: too many values to unpack

Tuples and lists

Tuples look like read-only lists . however , Tuples are most commonly used in single items that consist of multiple parts . A list is usually a collection of items of the same type ,

record = ('GOOG', 100, 490.1) # A tuple representing a record in a portfolio
symbols = [ 'GOOG', 'AAPL', 'IBM' ] # A List representing three stock symbols

Dictionaries

A dictionary is a key to value mapping . Sometimes , Dictionaries are also called hash tables (hash table) Or associative arrays (associative array). The key is used as an index to access the value .

s = {
'name': 'GOOG',
'shares': 100,
'price': 490.1
}

Common operations

To get a value from a dictionary , Please use key name .

>>> print(s['name'], s['shares'])
GOOG 100
>>> s['price']
490.10
>>>

To add or modify values , Please use key name to assign .

>>> s['shares'] = 75
>>> s['date'] = '6/6/2007'
>>>

To delete a value , Please use del sentence .

>>> del s['date']
>>>

Why use dictionaries ?

When there are many different values and it is possible to modify or manipulate them , Dictionaries are very useful . Dictionaries make code more readable .

s['price']
# vs
s[2]

practice

In the last few exercises , Write a data file Data/portfolio.csv The program . Use csv modular , It's easy to read files line by line .

>>> import csv
>>> f = open('Data/portfolio.csv')
>>> rows = csv.reader(f)
>>> next(rows)
['name', 'shares', 'price']
>>> row = next(rows)
>>> row
['AA', '100', '32.20']
>>>

Although it's easy to read files , But compared to reading data , Usually you use data to do more . for example , Maybe you want to store it and perform some calculations on it . Unfortunately , Raw data “ That's ok ” It can't be done . for example , Not even simple mathematical calculations .

>>> row = ['AA', '100', '32.20']
>>> cost = row[1] * row[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>>

To do more , Often the raw data needs to be interpreted in some way , And convert it to a more useful object type , For later processing . There are two simple ways to choose : Tuples or dictionaries .

practice 2.1: Tuples

At the interactive prompt , Create the following tuple representing the previous line , But the number column has to be converted to the right number .

>>> t = (row[0], int(row[1]), float(row[2]))
>>> t
('AA', 100, 32.2)
>>>

In this way , Now you can use the number of shares multiplied by the price to calculate the total price ,

>>> cost = t[1] * t[2]
>>> cost
3220.0000000000005
>>>

stay Python in , Is math useless ? Why did it turn out to be 3220.0000000000005?

This is the product of floating point hardware on the computer , Only in binary ( Not decimal ) The number of decimals is exactly expressed in . Even simple calculations involving decimal fractions , It also introduces small errors . This is normal , If you haven't seen it before , It might be a bit of a surprise .

Although this happens in all programming languages that use floating-point decimals , But you can hide it when you print , for example :

>>> print(f'{cost:0.2f}')
3220.00
>>>

Tuples are read-only . You can try to change the number of shares to 75 To test this .

>>> t[1] = 75
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>

Although the contents of tuples cannot be changed , But you can always create a new tuple to replace the old one .

>>> t = (t[0], 75, t[2])
>>> t
('AA', 75, 32.2)
>>>

Whenever you reassign an existing variable name like this , Old values are discarded . Although the assignment above might look like a tuple modification , But it's actually creating a new tuple , And discard the old tuples .

Tuples are often used to package or unpack values into variables . Please try the following :

>>> name, shares, price = t
>>> name
'AA'
>>> shares
75
>>> price
32.2
>>>

Take the variables above and package them back into tuples :

>>> t = (name, 2*shares, price)
>>> t
('AA', 150, 32.2)
>>>

practice 2.2: Treat dictionary as data structure

You can create dictionaries instead of tuples .

>>> d = {
'name' : row[0],
'shares' : int(row[1]),
'price' : float(row[2])
}
>>> d
{'name': 'AA', 'shares': 100, 'price': 32.2 }
>>>

Calculate the total amount held :

>>> cost = d['shares'] * d['price']
>>> cost
3220.0000000000005
>>>

Compare this example with the same calculation above involving tuples , Change the number of shares to 75.

>>> d['shares'] = 75
>>> d
{'name': 'AA', 'shares': 75, 'price': 32.2 }
>>>

Unlike tuples , Dictionaries are free to modify . Add some properties :

>>> d['date'] = (6, 11, 2007)
>>> d['account'] = 12345
>>> d
{'name': 'AA', 'shares': 75, 'price':32.2, 'date': (6, 11, 2007), 'account': 12345}
>>>

practice 2.3: Other operations of the dictionary

If you convert a dictionary into a list , Will get all of its keys :

>>> list(d)
['name', 'shares', 'price', 'date', 'account']
>>>

Similarly , If you use for Statement iterates over the dictionary , Will get all of its keys .

>>> for k in d:
print('k =', k)
k = name
k = shares
k = price
k = date
k = account
>>>

Try using this variant to perform the lookup at the same time :

>>> for k in d:
print(k, '=', d[k])
name = AA
shares = 75
price = 32.2
date = (6, 11, 2007)
account = 12345
>>>

You can also use keys() Method to get all the keys :

>>> keys = d.keys()
>>> keys
dict_keys(['name', 'shares', 'price', 'date', 'account'])
>>>

ad locum ,keys() It's a little different , What it returns is a dict_keys object .

This is an overlay of the original dictionary , It always provides the key for the current dictionary —— Even if the dictionary changes . for example , Give it a try :

>>> del d['account']
>>> keys
dict_keys(['name', 'shares', 'price', 'date'])
>>>

Please note that , Although not called again d.keys() , But the key 'account' Vanished .

A more elegant way to use keys and values together is to use items() Method . This gets a tuple of key values (key, value).

>>> items = d.items()
>>> items
dict_items([('name', 'AA'), ('shares', 75), ('price', 32.2), ('date', (6, 11, 2007))])
>>> for k, v in d.items():
print(k, '=', v)
name = AA
shares = 75
price = 32.2
date = (6, 11, 2007)
>>>

If there is something similar to items tuples , Then you can use dict() Function to create a dictionary . Please try the following :

>>> items
dict_items([('name', 'AA'), ('shares', 75), ('price', 32.2), ('date', (6, 11, 2007))])
>>> d = dict(items)
>>> d
{'name': 'AA', 'shares': 75, 'price':32.2, 'date': (6, 11, 2007)}
>>>

Catalog | Previous section (1.7 function ) | Next section (2.2 Containers )

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

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

  1. Python pandas: using pandas to add row data, that is, adding dictionary data to dataframe according to row data cycle
  2. Python:将Flask测试应用部署到Deta
  3. Python:OAuth2第三方登录之Github
  4. Python:使用pydantic库进行数据校验
  5. Python:免费IP归属地查询接口
  6. Python:使用user-agents库解析浏览器信息
  7. Python:cached_property缓存对象的属性
  8. Python:打包配置文件 setup.py 详解
  9. Python:ORM(Object Relational Mapper)模块汇总整理
  10. Python:datetime时间UTC时间转东八区
  11. Python: deploying flash test application to deta
  12. Python: oauth2 GitHub for third party login
  13. Python: using pydantic library for data verification
  14. Python: free IP home location query interface
  15. Python: parsing browser information using user agents Library
  16. Python:cached_ Property to cache the properties of an object
  17. Python: packaging configuration files setup.py Detailed explanation
  18. Python: ORM (object relational mapper) module summary
  19. Python: datetime, UTC, turn to District 8, East
  20. python tkinter 将某一目录下的所有图片插入到docx文件中
  21. Python Tkinter inserts all the pictures in a directory into the docx file
  22. 解决忽略VScode中Python插件pylint报错的问题
  23. To solve the problem of ignoring the error of Python plug-in in vscode
  24. python 毫秒级时间,时间戳转换
  25. Python millisecond time, timestamp conversion
  26. python try except 出现异常时,except 中如何返回异常的信息字符串
  27. When an exception occurs in Python try except, how to return the exception information string in except
  28. 手机最强Python编程神器,在手机上运行Python
  29. The strongest Python Programming artifact on mobile phones, running Python on mobile phones
  30. 2021年Python程序员薪资待遇如何?
  31. 「python安装」Windows上安装和创建python开发环境
  32. What is the salary of Python programmers in 2021?
  33. "Python installation" to install and create a python development environment on Windows
  34. python解决组合问题
  35. Python to solve the problem of composition
  36. Python中的Lasso回归之最小角算法LARS
  37. Lars, the least angle algorithm of lasso regression in Python
  38. 利用python提取网站曲线图数据
  39. Using Python to extract website graph data
  40. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
  41. Detailed usage of urllib in Python 3 (header, proxy, timeout, authentication, exception handling)
  42. python 第三方库paramiko
  43. python 第三方库paramiko
  44. Python third party library paramiko
  45. Python third party library paramiko
  46. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  47. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  48. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  49. django学习-27.admin管理后台里:对列表展示页面的数据展示进行相关优化
  50. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  51. Django learning - 27. Admin management background: optimize the data display of the list display page
  52. python day2
  53. python day2
  54. Python 内存泄漏问题排查
  55. Troubleshooting of Python memory leak
  56. Python 与 excel的简单应用
  57. Simple application of Python and excel
  58. Python 与 excel的简单应用
  59. Simple application of Python and excel
  60. 2.7万 Star!最全面的 Python 设计模式集合