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. 什么是java path环境变量

    参考:https://docs.oracle.com/javase/tutorial/essential/environment/paths.html 从orcle官网的文档中可以看到java pat ...

  2. C#反序化json字符串,不用区分大小写

    最近在做第三方对接的项目,接口返回的数据是json格式,并且每个字段都是小写的,而我们程序类中的属性是要求大写的:刚开始想到的是用JavaScriptSerializer,但是这个并不满足需求 就换了 ...

  3. 自己用js写的日历(在考勤中使用,显示员工的日期的考勤情况)

    1.HTML部分 <div id="AttendanceDataDetailDiv"> <div class="A_close"> &l ...

  4. SVN 使用锁实现独占式签出

      SVN默认并行工作,但是自动合并又做得很渣.团队工作中,如果确实有一些文件希望独占式签出可以使用SVN的特别属性.       Subversion针对此问题的解决方案是提供一种机制,提醒用户在开 ...

  5. Java基础知识学习(二)

    Java语法基础 数据类型.类型转换.运算符.逻辑运算符.参考C#,基本一致 输入输出 输出 System.out.print("abc"); System.out.printf( ...

  6. ajax异步上传到又拍云的实例教程

    作者:白狼 出处:www.manks.top/article/async_upload_to_upyun 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否 ...

  7. oracle 分析函数的使用(1)

    LISTAGG(columnName,'拼接符') WITHIN GROUP(ORDER BY clause) --order by 子句决定拼接内容的顺序 LISTAGG(columnName,'' ...

  8. 【JSP】JSP基础学习记录(三)—— JSP的9个内置对象

    本节说一下JSP中的9个内置对象.这9个内置对象都是Servlet API接口的实例,只是JSP规范对他们进行了默认初始化(由JSP页面对应Servlet的_jspService()方法来创建这些实例 ...

  9. 万能面试问题大全,教你怎么回答,怎么拿下offer

    一.你对薪资的要求? 回答提示: 说实话,大家找工作,都希望找个高薪的,那我们如何和公司去谈薪酬呢?如果你对薪酬的要求太低,那显然贬低自己的能力:如果你对薪酬的要求太高,那又会显得你分量过重,公司受用 ...

  10. Linux IPC System V 消息队列

    模型 #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> ftok() //获取key ...