Python 基础语法知识(二)

作者:无名 - 热门博客 -

四. input 读取输入值
在Python 2.x版本中,使用raw_input,但是到了Python 3.x,转变成input,帮助文档对该方法的说明如下:

input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

Example:
>>> s = input(&#39--> ')
--> Monty Python&#39s Flying Circus
>>> s
"Monty Python&#39s Flying Circus"


4.1. 输入字符串
nID = ''
while 1:
nID = input("Input your id plz:\n")
if len(nID) != len("123456789"):
print(&#39wring length of id,input again')
else:
break

print(&#39your id is %s' % (nID))

4.2.输入整数
nAge = int(input("input your age plz:\n"))
if nAge > 0 and nAge < 120:
print(&#39thanks!')
else:
print(&#39bad age')
print( &#39your age is %d\n' % nAge)

4.3. 输入浮点型
fWeight = 0.0
fWeight = float(input("input your weight: \n"))
print(&#39your weight is %f' % fWeight)

4.4. 输入16进制数据
nHex = int(input(&#39input hex value(like 0x20):\n'),16)
print( &#39nHex = %x,nOct = %d\n' %(nHex,nHex))

4.5. 输入8进制数据
nOct = int(input(&#39input oct value(like 020):\n'),8)
print (&#39nOct = %o,nDec = %d\n' % (nOct,nOct))


五. Enumerate 用法

帮助文档说明:
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), ....
For example:
>>> for i, season in enumerate([&#39Spring', &#39Summer', &#39Fall', &#39Winter']):
... print(i, season)
0 Spring
1 Summer
2 Fall
3 Winter

5.1 在for循环中得到计数
参数为可遍历的变量,如 字符串,列表等;返回值为enumerate类:
import string
s = string.ascii_lowercase
e = enumerate(s)
print(s)
print(list(e))

输出为:
>>>
abcdefghijklmnopqrstuvwxyz
[(0, &#39a'), (1, &#39b'), (2, &#39c'), (3, &#39d'), (4, &#39e'), (5, &#39f'), (6, &#39g'), (7, &#39h'), (8, &#39i'), (9, &#39j'), (10, &#39k'), (11, &#39l'), (12, &#39m'), (13, &#39n'), (14, &#39o'), (15, &#39p'), (16, &#39q'), (17, &#39r'), (18, &#39s'), (19, &#39t'), (20, &#39u'), (21, &#39v'), (22, &#39w'), (23, &#39x'), (24, &#39y'), (25, &#39z')]
>>>
在同时需要index和value值的时候可以使用 enumerate。

5.2 enumerate 实战
line 是个 string 包含 0 和 1,要把1都找出来:
#方法一
def read_line(line):
sample = {}
n = len(line)
for i in range(n):
if line[i]!=':
sample[i] = int(line[i])
return sample

#方法二
def xread_line(line):
return((idx,int(val)) for idx, val in enumerate(line) if val != ')

print( read_line(&#390001110101'))
print( list(xread_line(&#390001110101')))


六. yield 用法
The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to generator’s caller. By suspended we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression was just another external call. The value of the yield expression after resuming depends on the method which resumed the execution.
All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where should the execution continue after it yields; the control is always transferred to the generator’s caller.
The yield statement is allowed in the try clause of a try ... finally construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.


yield 简单说来就是一个生成器,生成器是这样一个函数,它记住上一次返回时在函数体中的位置。对生成器函数的第二次(或第 n 次)调用跳转至该函数中间,而上次调用的所有局部变量都保持不变。

(1)生成器是一个函数:函数的所有参数都会保留
(2)第二次调用 此函数 时:使用的参数是前一次保留下的.
(3)生成器还“记住”了它在流控制构造:生成器不仅“记住”了它数据状态。 生成器还“记住”了它在流控制构造(在命令式编程中,这种构造不只是数据值)中的位置。由于连续性使您在执行框架间任意跳转,而不总是返回到直接调用者的上下文(如同生成器那样),因此它仍是比较一般的。 http://www.csvt.net/

yield 生成器的运行机制
当问生成器要一个数时,生成器会执行,直至出现 yield 语句,生成器把 yield 的参数给你,之后生成器就不会往下继续运行。当你问他要下一个数时,他会从上次的状态开始运行,直至出现yield语句,把参数给你,之后停下。如此反复直至退出函数。


6.1 Yield 应用

#生成全排列
def perm(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p

#生成组合
def comb(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[i+1:]
for c in comb(rest, n-1):
yield v + c

a = perm(&#39abc')
for b in a:
print(b)
break
print(&#39-'*20)
for b in a:
print(b)

a = perm(&#39abc')
for b in a:
print(b)
break
print(&#39-'*20)
for b in a:
print(b)

执行结果:
abc
--------------------
acb
bac
bca
cab
cba
abc
--------------------
acb
bac
bca
cab
cba

在第一个循环break后,生成器没有继续执行,而第二个循环接着第一个循环执行

http://www.csvt.net/

以上就是由(IT人知识库http://www.itpeo.net/149394/3708470.html)本站为大家整理





金融行业等级保护F项解读

 金融行业增强安全保护类(F类)要求是在结合等级保护及金融行业相关规定的基础上进行补充和完善。使得本实施... ...

java中的String,StringBuffer和StringBuilder

昨天又面试了,面试中问道了一个技术问题。StringBuffer和StringBuilder的区别。由于很久没有做... ...

初涉SEM必知 切勿将自己变成IT民工

 随着近年来互联网技术与应用的飞速发展,作为网络营销的代表者,SEM已然成为众多企业特别是中小企业市场业... ...

传统服务业/零售业的电商O2O之道

   电商市场的快速发展对实体终端零售业造成的影响越来越严重了,图书市场就是重灾区。另外,由于很多消费者... ...

四月电商战 京东突围与苏宁国美当当再围剿

   四月的电商战火已经燃起,苏宁国美当当联合围剿京东商城,京东已经受困。苏宁国美当当此次掀起电商价格战... ...

2007-2010三年IT心路历程(二)

        2009年年末是我人生的一... ...

中端存储不能承受之重

时至今日,中端存储已经成了各存储厂商最倚重的一条产品线。中端存储承受了太多的“压力”,比如高端技术下移,追... ...

闪存市场流行并购风

传统硬盘市场经过几轮洗牌之后,基本形成了希捷、西部数据两家对峙之势。硬盘市场变化的诱因之一就是固态硬盘(S... ...

HP 3PAR在中国起航

我们已经进入了大数据(Big Data)时代。IDC预测,2011年全球数据总量将达到700PB。未来,数据将以年... ...

Linux Kernel 2.4.x / 2.6.x uselib() Local Privilege Escalation Exploit

/* * pwned.c - linux 2.4 and 2.6 sys_uselib local root e... ...

Lesson 1:单线程 Socket Communications(一)

1. 服务器端  package socket; import java.awt.Color; im... ...

POI读取Excel 初步支持对象封装功能

package com.randy; import java.beans.B... ...

关于NP架构防火墙的发展

关于NP架构防火墙的发展 NP架构防火墙在去年是业界的一个关注点,... ...

Carl the Ant的翻译

这是ACM上的一道题目:http://acm.zju.edu.cn/onlinejudge/showProblem... ...

社区电子商务是一种从众经济

  美国《福布斯》杂志网络报道:Facebook电子商务前景广阔。 文章介绍说,Facebook... ...

Lbs:能为商家带来回头客的移动应用

 仅用一年多的时间,美国最大的位置服务商Foursquare就聚集了300多万手机用户,另外一款lbs应... ...

字符编码cp936

做东西的时候突然遇到字符变魔术cp936的编码,当时蒙了,最后通过查手册和资料知道cp936就是指系统里第936号... ...

CentOS-5安装配置ExtMail Web邮件收发系统

本文参考http://wiki.extmail.org/extmail_solution_for_linux_ce... ...

经常从梦中惊醒

经常从梦中惊醒 清凉的风从窗口逃窜到我的胸口  又是这种感觉, 又是这样没有理由地折磨自... ...

安装server 2003和xp可能遇到的问题

由于自己以前装fedora core(linux)的缘故,自己硬盘的分区是那么零碎.并且交换分区也就那么1... ...