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. 终极指南:如何为iOS8应用制作预览视频

    最近一两个月里,苹果的世界里出现了很多新东西,比如屏幕更大的iPhone 6,可穿戴设备Apple Watch,iOS8,以及旨在帮助用户更好的发现应用的App Store改版等等. 说到App St ...

  2. 搭建Maven私服

    最近从SVN下载的代码,在本地构建时出现了诸多问题,部分依赖下载超时,就想起在局域网搭建Maven私服,废话不说了,在测试服务器上建的已经成功,就随便找台机子再练习一遍顺道写个日志.1.前往http: ...

  3. android 界面设计基本知识Ⅲ

    本章继续讲述在android界面设计中相关的知识点.介绍内容包括BroadcastReceiver(广播),Service(服务),Widget(小部件),WebView(网页加载控件). 1.Bro ...

  4. runtime之玩转成员变量

    前言: 不铺垫那么多,单刀直入吧:runtime是一个C和汇编写的动态库,就像是一个小小的系统,将OC和C紧密关联在一次,这个系统主要做两件事情. 1,封装C语言的结构体和函数,让开发者在运行时创建, ...

  5. js 使某个页面不允许在子iframe中打开的解决办法

    在页面中添加如下js代码<script> if (window.parent !== window.self) { window.parent.location.reload(); }&l ...

  6. Android简单加密保护自有图片资源

    现在大部分android应用的图片资源,被反编译后就可以直接拿来用,如果不想让自己的图片资源直接被反编译后使用,首先想到的应该是把图片加密.这里笔者抛砖引玉,草草写了一个对图片进行简单加密的方法,希望 ...

  7. GlassFish: 001 安装、启动

    安装 在GlassFish项目的首页就可以找到如何安装: https://glassfish.java.net/download.html#gfoseTab 上面给出了5个步骤:0,1,2,3,4 第 ...

  8. mysql metadata lock(二)

    上一篇<mysql metadata lock(一)>介绍了为什么引入MDL,MDL作用以及MDL锁导致阻塞的几种典型场景,文章的最后还留下了一个小小的疑问.本文将更详细的介绍MDL,主要 ...

  9. 0002 Oracle账户相关的几个语句

    Oracle安装完成后,在“开始”里找到SQL Plus运行,要求输入帐号和密码,用system/密码连接. 1.Oracle里有一个默认的scott账户密码tiger,用该账户连接: CONN 用户 ...

  10. SQL查询数据库中所有指定类型的字段名称和所在的表名

    --查询数据库中所有指定类型的字段名称和所在的表名 --eg: 下面查的是当前数据库中 所有字段类型为 nvarchar(max) 的字段名和表名 SELECT cols.object_id , co ...