## 翻译：《实用的Python编程》02_01_Datatypes

codists 2021-02-20 21:58:32

# 2.1 数据类型和数据结构

### 原始数据类型

Python 有一些原始数据类型：

• 整数
• 浮点数
• 字符串（文本）

### 空类型

``email_address = None``

`None` 常用作可选值或缺失值的占位符。它在条件语句中计算为 `False`

``````if email_address:

### 数据结构

``100 shares of GOOG at \$490.10``

• 股票的名称或符号（"GOOG"，字符串）
• 股份数目（100，整数）
• 价格（490.10，浮点数）

### 元组

``s = ('GOOG', 100, 490.1)``

``s = 'GOOG', 100, 490.1``

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

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

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

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

### 元组打包

``s = ('GOOG', 100, 490.1)``

### 元组拆包

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

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

### 元组与列表

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

### 字典

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

### 常见操作

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

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

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

### 为什么使用字典？

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

## 练习

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

``````>>> 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'
>>>``````

### 练习 2.1：元组

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

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

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

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

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

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

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

### 练习 2.2：把字典当作数据结构

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

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

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

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

### 练习 2.3: 字典的其它操作

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

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

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

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

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

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

``````>>> 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)}
>>>``````

https://segmentfault.com/a/1190000039242464