【编程语言】Python3 笔记

2016-05-07  本文已影响59人  苏尚君

Python3

差异

常见第三方库 http://awesome-python.com/ [1]

导入库/模块

导入库:

import <library name> # 用库的名字替换<library name>

这条命令后,使用该库下的模块<module name>时,应输入 <library name>.<module name>

导入模块:

from <library name> import <module name> # 从名为 <library name> 的库中导入名为 <module name> 的模块

这条命令后,使用该模块<module name>时,只要输入 <module name>即可

特色数据结构

主要有 4 种:

数据结构技巧

列表排序[1]

sorted(<list>) 将返回名为 <list> 的列表排序后的结果

使用可选参数 reverse = Truesorted(<list>, reverse = True) 返回逆序列表

注意,python 并不是按 ASCII 码排序的,仅支持列表中元素类型一致情况下的排序。例如,当列表中既有字符又有数字时,排序将报错

多重列表[1]

要同一 for 循环中同时遍历两个列表,请使用 zip 函数。循环进行到包含元素较少的列表遍历尽为止。

例如:

# i 是列表 charList 中的项目
# j 是列表 numList 中的项目
for i, j in zip(charList, numList):
    print('The code for {} is {}.'.format(i, j))

列表推导式/列表解析式(List Comprehension)[1]

该方法书写简短,效率比普通 for 循环高。

基本语法:

i = [<function(<item>)> for <item> in <list for items>]

例如:

fruitList = ['apple', 'peach', 'orange']
i = [fruit[0] for fruit in fruitList] # 本句之后, i = ['a', 'p', 'o']

循环列表时获取元素索引[1]

enumerate(<list>) 将返回一个列表(元组?),其中每个对象为一个元组,元组中包含 2 个元素:首元素为索引 <index>,次元素为列表 <list> 中对应索引 <index> 的元素。

假设现有列表 fruitList = ['apple', 'peach', 'orange'],则下述代码:

for fruit,i in enumerate(fruitList):
     print(fruit)
     print(i)

将打印

0
apple
1
peach
2
orange

列表扩展[2]

如下代码将把列表 L1 中所有元素添加到列表 L0 中:

L0.extend(L1)

字符串处理

在字符串 strA 中剥去子串 strB[3]

strA.strip(strB)

一些常用库的简介

参考资料


  1. Python实战:四周实现爬虫系统

  2. 5. Data Structures

  3. 4. Built-in Types - str.strip

上一篇 下一篇

猜你喜欢

热点阅读