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. 【代码笔记】iOS-设置textView或者label的行间距方法

    一,效果图. 二,代码. RootViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional se ...

  2. OC中的内存管理

    一. 基本原理 1. 什么是内存管理 移动设备的内存极其有限,每个app所能占用的内存是有限制的 当app所占用的内存较多时,系统会发出内存警告,这时得回收一些不需要再使用的内存空间.比如回收一些不需 ...

  3. push notification获取device token

    第一步:申请证书: 第二步:申请app ids,应用名字必须一致.然后再进入进行编辑,使其enable,绿灯. 第三步:申请provisioning profile,生成.mobileprovisio ...

  4. WebServer中异步操作的一些总结

    1.异步操作本身不会改善IO的性能 2.当任务多为IO操作时普通的工作线程将会减少,使CPU对工作线程的维护降低,从而提高CPU对其它任务的利用率 3.如果专用的IO线程,需要执行的专用任务较多时,专 ...

  5. BIEE使用技巧

    索引: 1.如何清除缓存 2.通过“编辑 SQL”取得前一天的日期 3.格式化日历框参数 4.根据传入的开始时间和结束时间取得事实表中的指标(用到了3中的技巧) 5.直接调用数据库函数 6.时间格式转 ...

  6. Third glance in Go

    在Go語言裏關於數組(Array),切片(Slice)和映射表(Map)的使用是非常常見的.有過其他語言編程背景的人會比較熟悉一下,但是也是因爲過於的熟悉,從而導致一個慣性思維,往往就會踢到“石頭”, ...

  7. 看看Parallel中高度封装的三个方法,Invoke,For和ForEach

    说到.net中的并行编程,也许你的第一反应就是Task,确实Task是一个非常灵活的用于并行编程的一个专用类,不可否认越灵活的东西用起来就越 复杂,高度封装的东西用起来很简单,但是缺失了灵活性,这篇我 ...

  8. mysql-mmm 安装配置(双主)

    原文地址:mysql-mmm 安装配置 作者:chinaunix1116 MMM即Master-Master Replication Managerfor MySQL(mysql主主复制管理器)关于m ...

  9. java 的常用设计模式--大话设计模式

    设计模式:一个程序员对设计模式的理解:“不懂”为什么要把很简单的东西搞得那么复杂.后来随着软件开发经验的增加才开始明白我所看到的“复杂”恰恰就是设计模式的精髓所在,我所理解的“简单”就是一把钥匙开一把 ...

  10. 简单阐述下Ajax以get方式请求的步骤 初学,不对的话,跟我说下,谢谢!

    首先, 在GET提交中"=,&"等字符与请求字符串的关键字相混淆.所以: 第一步,先对get提交过来的数据进行编码. 第二步,实例化ajax对象. 第三步,创建对服务器的连 ...