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的更多相关文章

  1. Meet Python: little notes 3 - function

    Source: http://www.liaoxuefeng.com/ ♥ Function In python, name of a function could be assigned to a ...

  2. Meet Python: little notes 2

    From this blog I will turn to Markdown for original writing. Source: http://www.liaoxuefeng.com/ ♥ l ...

  3. Meet Python: little notes

    Source: http://www.liaoxuefeng.com/ ❤ Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...

  4. python 100day notes(2)

    python 100day notes(2) str str2 = 'abc123456' print(str1.endswith('!')) # True # 将字符串以指定的宽度居中并在两侧填充指 ...

  5. [Python Study Notes]异常处理

    正则表达式 python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误.你可以使用该功能来调试python程序. 异常处理 断言(Assertions) python标准异常 ...

  6. 70个注意的Python小Notes

    Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要.旨在注意一些细节问题,在今后项目中灵活运用 ...

  7. 【leetcode❤python】102. Binary Tree Level Order Traversal

    #-*- coding: UTF-8 -*-#广度优先遍历# Definition for a binary tree node.# class TreeNode(object):#     def ...

  8. [Python Study Notes]匿名函数

    Python 使用 lambda 来创建匿名函数. lambda这个名称来自于LISP,而LISP则是从lambda calculus(一种符号逻辑形式)取这个名称的.在Python中,lambda作 ...

  9. [Python Study Notes]字符串处理技巧(持续更新)

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...

随机推荐

  1. 移动Web开发(一)

    1.浅谈Web标准 降低开发复杂度,覆盖的技术层面十分广泛,技术标准化. 以HTML为核心,扩展出几个大类的技术标准: a.程序访问: ECMAScript(ES) 3 . ES 5 . ES ham ...

  2. 【代码笔记】iOS-登陆单例

    一,工程图. 二,代码. UserInfo.h #import <Foundation/Foundation.h> @interface UserInfo : NSObject + (id ...

  3. sdk的目录结构及其功能

    sdk的目录结构及其功能 add-ons: 这里面保存着附加库,比如GoogleMaps,当然你如果安装OphoneSDK,这里也会有一些类库在里面. build-tools: 各个版本的sdk编译工 ...

  4. IOS设计模式-观察者模式

    前言:23种软件设计模式中的观察者模式,也是在软件开发中,挺常用的一种设计模式.而在苹果开发中,苹果Cocoa框架已经给我们实现了这个设 计模式,那就是通知和KVO(Key-Value Observi ...

  5. 转:能和LoadRunner匹敌的VS2010/2012Web负载测试

    原文出处:http://www.cnblogs.com/aarond/archive/2013/04/18/performance.html VS自带的Web负载测试真的很大程度上能和专业的loadr ...

  6. 跨域调用webapi web端跨域调用webapi

    web端跨域调用webapi   在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webap ...

  7. Sqlite学习笔记(一)&&编译安装

    Sqlite简介 sqlite是一个开源的嵌入式文件数据库,sqlite以动态链接库的方式供应用程序调用,所有的数据库对象都存储在同一个文件中. sqlite动态库非常小,最新的3.8.11版本也只有 ...

  8. mysql源码解读之配置文件

    要研究mysql,最好的资源莫过于源码了,所以本人打算通过调试源码的方式来深入理解mysql的点点滴滴.搭建mysql调试环境很简单,从官方下载mysql源码,利用cmake工具生成工程即可.为了方便 ...

  9. TSQL--临时表和表变量

    1. 临时表适用数据量较大的情况,因为临时表可以建立索引 2. 表变量适用于数据较小的情况,表变量只能在定义时创建约束(PRIMARY KEY/UNIQUE)从而间接建立索引 3. 临时表是事务性的, ...

  10. 预写式日志(Write-Ahead Logging (WAL))

    SQL Server中使用了WAL(Write-Ahead Logging)技术来保证事务日志的ACID特性.而且大大减少了IO操作. WAL的核心思想是:在数据写入到数据库之前,先写入到日志.再将日 ...