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]字符串处理技巧(持续更新)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...
随机推荐
- iOS 滑动隐藏导航栏-三种方式
/** 1隐藏导航栏-简单- */ self.navigationController.hidesBarsOnSwipe = YES; /** 2隐藏导航栏-不随tableView滑动消失效果 ...
- 【代码笔记】iOS-竖排文字
一,代码. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ...
- Xcode常见错误汇总
1.error: macro names must be identifiers YourProject_prefix.pch 原因: 因为你弄脏了预处理器宏,在它处于<Multiple Val ...
- 【Android疑难杂症】GridView动态设置Item的宽高导致第一个Item不响应或显示不正常的问题
前言 这个问题在之前做一个盒子项目时遇到过,最近又遇到了,使用GridView遇到的非常奇葩的问题,这里记录分享一下. 声明 欢迎转载,但请保留文章原始出处:) 博客园:http://www.cnb ...
- Github上十大C#开源项目排行榜
1.SignalR ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.当WebSockets可用时(即浏览器支持Ht ...
- ORACLE手工删除数据库
很多人习惯用ORACLE的DBCA工具创建.删除数据库,这里总结一下手工删除数据库实验的步骤,文中大量参考了乐沙弥的手动删除ORACLE数据库这篇博客的内容,当然还有Oracle官方相关文档.此处实验 ...
- Spring源码阅读系列总结
最近一段时间,粗略的查看了一下Spring源码,对Spring的两大核心和Spring的组件有了更深入的了解.同时在学习Spring源码时,得了解一些设计模式,不然阅读源码还是有一定难度的,所以一些重 ...
- SQL动态列查询
数据库中为了实现表格数据的自由设置,我们经常设计纵表,或者列定义的表(如下KeyValue),定义一个列超级多的表中每个字段的意义. 但是在设计时简单的东西却很容易被人们忘记,如下一个简单但是很松散的 ...
- 朝花夕拾之--大数据平台CDH集群离线搭建
body { border: 1px solid #ddd; outline: 1300px solid #fff; margin: 16px auto; } body .markdown-body ...
- Windows环境下载与安装JBOSS服务器的详细图文教程
一.JDK的安装 首先安装JDK,配置环境变量(PATH,CLASSPATH,JAVA_HOME). 可以参照:Windows环境下JDK安装与环境变量配置 二.Jboss的介绍 JBOSS是EJB的 ...