Meet python: little notes 4 - high-level characteristics
Source: http://www.liaoxuefeng.com/
♥ Slice
Obtaining elements within required range from list or tuple (The results remain the same type as the original one.).
>>> L = list(range(100))
>>> L
[0, 1, 2, ..., 99]
>>> L[:3] # Access first three indexed elements, i.e. [0 1 2], 0 could be ...
[0, 1, 2] # omitted being the first index
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[:10:2] # The third number denote the slice interval
[0, 2, 4, 6, 8]
>>> (0, 1, 2, 3, 4, 5)[:3] # An example for tuple
(0, 1, 2)
>>> 'ABCDEF'[1:2] # An example for string
'B'
♥ Interation
- Using for...in to tranverse a list, tuple or other kinds of iterable structure.
# dictionary: note that keys in a dict are not scored in the list order
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d
print(key)
a
b
c
# string
>>> for ch in 'ABC'
print(ch)
A
B
C
# Decide if an object is an iterable object
>>> from collections import Iterable
>>> isinstance(123, Iterable)
False # Integer is not iterable
- Realise ordered iteration: enumerate
>>> for i, value in enumerate(['A', 'B', 'C']) # change a list to key-value
# pair
print(i, value)
0 A
1 B
2 C
♥ List comprehensions
Construct a list.
# Normal way
>>> L = []
>>> for x in range(1, 11)
l.append(x * x)
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# List comprehension
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Double deck
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
# Construct a list using two variables with list comprehension
>>> d = {'x': 'A', 'y': 'B', 'z': 'C'}
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
♥ Generator
- A special iterable function.
- One characteristic of generator is that it breaks every time when coming across yield, restarts at exactly where it breaks last time next calling, and will not return a value unless meeting stopIteration (return value is included there). Examples of constructing a generator and calling:
# First way to produce a generator
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Change [] to (), a generator is obtained instead of a list
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
# Second way: yield.
def fib(max): # Fibonacci sequence
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
>>> g = fib(6)
>>> while True:
... try:
... x = next(g) # obtain next elements in generator
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
♥ Iterator
- Object can be called using next() and return next value, actually a data flow.
- Note, iterator is different from iterable.
>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance([], Iterable)
False
# Invert an iterable to iterator.
>>> isinstance(iter([]), Iterator)
True
- Advantage: iterator is an ordered sequence, but will not calculate next value unless required, thus is of efficiency.
- Summary
objects can be used in for are iterables;
all generators are iterators;
iterebles can be converted to iterators via iter().
Meet python: little notes 4 - high-level characteristics的更多相关文章
- Meet Python: little notes 3 - function
Source: http://www.liaoxuefeng.com/ ♥ Function In python, name of a function could be assigned to a ...
- Meet Python: little notes 2
From this blog I will turn to Markdown for original writing. Source: http://www.liaoxuefeng.com/ ♥ l ...
- Meet Python: little notes
Source: http://www.liaoxuefeng.com/ ❤ Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...
- python 100day notes(2)
python 100day notes(2) str str2 = 'abc123456' print(str1.endswith('!')) # True # 将字符串以指定的宽度居中并在两侧填充指 ...
- [Python Study Notes]异常处理
正则表达式 python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误.你可以使用该功能来调试python程序. 异常处理 断言(Assertions) python标准异常 ...
- 70个注意的Python小Notes
Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要.旨在注意一些细节问题,在今后项目中灵活运用 ...
- 【leetcode❤python】102. Binary Tree Level Order Traversal
#-*- coding: UTF-8 -*-#广度优先遍历# Definition for a binary tree node.# class TreeNode(object):# def ...
- [Python Study Notes]匿名函数
Python 使用 lambda 来创建匿名函数. lambda这个名称来自于LISP,而LISP则是从lambda calculus(一种符号逻辑形式)取这个名称的.在Python中,lambda作 ...
- [Python Study Notes]字符串处理技巧(持续更新)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...
随机推荐
- NSPredicate
NSPredicate 1. 正则表达式使用单个字符串来描述.匹配一系列符合某个句法规则的字符串.通常被用来检索.替换那些符合某个模式的文本. 2. iOS中正则使用 有三种(NSPredicate, ...
- c中的进制与内存分析
一. 进制 1. 什么是进制 l 是一种计数的方式,数值的表示形式 数一下方块的个数 汉字:十一 十进制:11 二进制:1011 八进制:13 l 多种进制:十进制.二进制.八进制.十六进制. ...
- 转载文章----初识Ildasm.exe——IL反编译的实用工具
转载地址http://www.cnblogs.com/yangmingming/archive/2010/02/03/1662307.html Ildasm.exe 概要:(路径:C:\Program ...
- android Activity生命周期(设备旋转、数据恢复等)与启动模式
1.Activity生命周期 接下来将介绍 Android Activity(四大组件之一) 的生命周期, 包含运行.暂停和停止三种状态,onCreate.onStart.onResume.o ...
- 【转发】揭秘Facebook 的系统架构
揭底Facebook 的系统架构 www.MyException.Cn 发布于:2012-08-28 12:37:01 浏览:0次 0 揭秘Facebook 的系统架构 www.MyExcep ...
- fopen()、 file_get_contents() 通过url获取链接内容
功能:获得网页内容 区别如下: fopen()打开URL 下面是一个使用fopen()打开URL的例子: <?php $fh = fopen('http://www.baidu.com/', ' ...
- Access 2003 中自定义菜单栏
在Access中如何用自定义的菜单代替Access自带的菜单,现在做一个简单的介绍: 1.打开您做的Access数据库: 2.单击工具栏,选择“自定义…”: 3.在“自定义”窗口,单击“工具栏”选项卡 ...
- IE下innerText与FoxFire下textContent属性的不同
<div> 我是中国 人 我<br/>爱 自己 的<div>祖国</div>. <div> IE下输出 我是中国 人 我 爱 自己 的 祖国 ...
- 烂泥:【解决】VMware Workstation中安装ESXI5.0双网卡问题
本文由秀依林枫提供友情赞助,首发于烂泥行天下. 由于需要做ESXI相关的实验,所以就在自己的机器上利用VM虚拟ESXI进行实验.因为此次实验是需要两块网卡的,所以就在创建ESXI虚拟机时添加了两块网卡 ...
- linux下文件的特殊权限s和t
先看看这两个文件的权限:[root@localhost ~]# ls -ld /usr/bin/passwd /tmpdrwxrwxrwt 4 root root 4096 Jun 2 17:33 / ...