In [1]: a = {1:2, 2:3, 3:4}
In [2]: tuple(a)
Out[2]: (1, 2, 3)
tuple() 对 dict 强制类型转换是取 keys。
In [22]: a = (1, 2, 3, 4, 3, 4)
In [23]: a.index(3)
Out[23]: 2
tuple 还有一个 index method:
tuple.index(element)
找到的是第一个出现的 element。
dict() 函数
The dict() constructor builds dictionaries directly from sequences of key-value pairs.
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
如果 a = ['sape', 'guido', 'jack'],b = [4139, 4127, 4098],那么如何变成 [('sape', 4139), ('guido', 4127), ('jack', 4098)]?用前面学过的 zip() 函数。记住 zip() 是个 lazy iterator。
>>> a = ['sape', 'guido', 'jack']
>>> b = [4139, 4127, 4098]
>>> zip(a, b)
>>> type(zip(a, b))
<class 'zip'>
>>> dict(zip(a, b))
{'sape': 4139, 'guido': 4127, 'jack': 4098}
这种方式叫 dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs。
>>> {zip(a, b)}
{<zip object at 0x108924280>}
用花括号 {} 就无法构建出一个这样的 dictionary。但是用 {} 和 dict() 都可以构建一个空字典。
dict() 函数还有一种构建字典的方式叫 dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list.
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
dict() 函数还有一种构建字典的方式叫 dict(iterable)。iterable 可以用 dict comprehension 来实现。
>>> dict((x, x**2) for x in (2, 4, 6))
{2: 4, 4: 16, 6: 36}
这种方式也可以直接用 {} 来操作:
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
看看两个用法还是有区别的。
第 89 页:为什么 numpy.empty() 生成的不是非空的 array?看这里的讨论。
第 91 页:Numpy data type 也可以延续用 Python 的 int, float, str, bool, bytes ... 等数据类型
int 对应的是 numpy.init32
In [1]: import numpy as np
In [2]: a = np.array([1, 2, 3], dtype=int)
In [3]: a.dtype
Out[3]: dtype('int32')
float 对应的是 numpy.float64
In [4]: a = np.array([1, 2, 3], dtype=float)
In [5]: a.dtype
Out[5]: dtype('float64')
str 对应的是 numpy.unicode_
In [7]: a = np.array([1, 2, 3], dtype=str)
In [8]: a.dtype
Out[8]: dtype('<U1')
In [9]: a = np.array(['1', '2', '30000'], dtype=str)
In [10]: a.dtype
Out[10]: dtype('<U5')
In [17]: arr = np.array([[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]])
In [20]: arr[[0, 2], [1, 2]]
Out[20]: array([2, 9])
相当于取第一行和第二列 (0, 1),和取第三行和第三列 (2, 2) 的元素然后组成了一个一维 numpy.array。
No comments:
Post a Comment