深入Python3学习备忘记录

Python 中有许多内置数据类型。以下是比较重要的一些:
  1. Booleans【布尔型】 或为 True[真] 或为 False[假]。
  2. Numbers【数值型】 可以是 Integers【整数】(1 和 2)、Floats【浮点数】(1.1 和 1.2)、Fractions【分数】(1/2 和 2/3);甚至是 Complex Number【复数】。
  3. Strings【字符串型】 是 Unicode 字符序列,例如: 一份 html 文档。
  4. Bytes【字节】 和 Byte Arrays【字节数组】, 例如: 一份 jpeg 图像文件。
  5. Lists【列表】 是值的有序序列。
  6. Tuples【元组】 是有序而不可变的值序列。
  7. Sets【集合】 是装满无序值的包裹。
  8. Dictionaries【字典】 是键值对的无序包裹。

>>> math.tan(math.pi / 4)
0.9999999999999999
>>> 0.999999999999999 == math.tan(math.pi/4)
False
元组可转换成列表,反之亦然。内建的 tuple() 函数接受一个列表参数,并返回一个包含同样元素的元组,而 list() 函数接受一个元组参数并返回一个列表。从效果上看,  tuple()  冻结列表,而  list()  融化元组
>>> type((False))
<class 'bool'>
>>> type((False,))
<class 'tuple'>
为创建单元素元组,必须在值之后加上一个逗号。 没有逗号,Python 会假定这只是一对额外的圆括号,虽然没有害处,但并不创建元组。 


常见的集合操作

>>> aset = {1,3,5,7,9}
>>> bset = {2,3,5,7}
>>> aset.union(bset)
{1, 2, 3, 5, 7, 9}
>>> aset.intersection(bset)
{3, 5, 7}
>>> aset.difference(bset)
{9, 1}
>>> aset.symmetric_difference(bset)
{1, 2, 9}
请记住: 集合是无序的。任何两个包含所有同样值(无一遗漏)的集合可认为是相等的。
>>>a_set = {1, 2, 3} 
>>>b_set = {1, 2, 3, 4} 
>>>a_set.issubset(b_set) 
True 
>>>b_set.issuperset(a_set)
True


交换字典的键和值

>>>a_dict = {'a': 1, 'b': 2, 'c': 3} 
>>>{value:key for key, value in a_dict.items()} 
{1: 'a', 2: 'b', 3: 'c'}


(format)替换域

>>>username = 'mark' 
>>>password = 'PapayaWhip' 
>>>"{0}'s password is {1}".format(username, password) 
"mark's password is PapayaWhip"

>>> import humansize, sys
>>> '1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys)
'1MB = 1000KB'
注意:在使用替换域的时候,我们在省略了字典的键名周围的引号(比如 humansize)

从技术上说,字符编码的重载声明也可以放在第二行,如果第一行被类unix系统中的hash-bang命令占用了:

#!/usr/bin/python3
# -*- coding: windows-1252 -*-


斐波那奇生成器

def fib(max):
    a, b = 0, 1          
    while a < max:
        yield a          
        a, b = b, a + b 
>>> from fibonacci import fib
>>> for n in fib(1000):      
...     print(n, end=' ')    
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> list(fib(1000))          
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

正则的一个补充:

>>> re.findall(' s.*? s', "The sixth sick sheikh's sixth sheep's sick.")
[' sixth s', " sheikh's s", " sheep's s"] 
很惊奇?这个正则表达式寻找一个空格,一个 s, 然后是最短的任何字符构成的序列(.*?), 然后是一个空格, 然后是另一个s。 在输入字符串中,我看见了五个匹配:
    The sixth sick sheikh's sixth sheep's sick.
    The sixth sick sheikh's sixth sheep's sick.
    The sixth sick sheikh's sixth sheep's sick.
    The sixth sick sheikh's sixth sheep's sick.
    The sixth sick sheikh's sixth sheep's sick.
但是re.findall()函数值只返回了3个匹配。准确的说,它返回了第一,第三和第五个。为什么呢?因为它不会返回重叠的匹配。第一个匹配和第二个匹配是重叠的,所以第一个被返回了,第二个被跳过了。然后第三个和第四个重叠,所以第三个被返回了,第四个被跳过了。最后,第五个被返回了。三个匹配,不是五个。

这和字母算术解决者没有任何关系;我只是觉得这很有趣。


你可能感兴趣的:(深入Python3学习备忘记录)