迭代的意思是重复做一些事很多次,到目前只是在for循环中对序列和字典进行迭代,但实际也能对其他的对象进行迭代,实现_iter_方法的对象。
_iter_方法返回一个迭代器,所谓的迭代器就是具有next方法(这个方法在调用时不需要任何参数)的对象。在调用next方法时,迭代器对返回它的下一个值。如果next方法被调用,但迭代器没有值可以返回,就会引发一个Stoperation异常。
In [11]: t = (1,2)
In [12]: it = iter(t) ##对元组进行迭代
In [13]: it.next()
1
In [14]: it.next()
2
In [15]: it.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-15-54f0920595b2> in <module>()
----> 1 it.next()
StopIteration: ##迭代器没有值可以返回,引发Stoperation异常
In [18]: c.next()
1
In [19]: c.next()
2
In [20]: c.next()
3
In [21]: c.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-21-50b4dad19337> in <module>()
----> 1 c.next()
StopIteration:
In [23]: for i in range(4):
....: print i
....:
0
1
2
3
####字典####
字典对象是可变的,但是字典的键必须是不可变对象,并且一个字典中可以使用不同类型的键值
In [37]: s = {}
In [38]: type(s)
dict
##集合为空,为字典格式
删除:del dic , del dic["key"], dic.pop["key"]
字典的查找:dic.keys(), dic.values(), dic.items()
In [26]: dic = {"name":"fentiao", "age":5, "gender":"male"}
>>> dic = {"name":"fentiao", "age":5, "gender":"male"}
>>> dic[0] ##为字典格式时,不能通过索引提取value值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
In [27]: type(dic)
dict ##字典格式
In [28]: dic.keys() ##查看字典的key
['gender', 'age', 'name']
In [29]: dic.values() ##查看字典的values
['male', 5, 'fentiao']
In [30]: dic.items()
[('gender', 'male'), ('age', 5), ('name', 'fentiao')]
In [31]: a,b = (1,2)
In [32]: for k,v in dic.items(): ##使用迭代器
....: print k,v
....:
gender male
age 5
name fentiao
print "k=%s,v=%s" %(k,v) ##优化输出格式
....:
k=gender,v=male
k=age,v=5
k=name,v=fentiao
In [60]: dic.itervalues() ##对字典中的values进行迭代
<dictionary-valueiterator at 0x2b0dec0>
In [61]: a = dic.itervalues()
In [62]: a.next()
'male'
In [63]: a.next()
5
In [64]: a.next()
'fentiao'
<dictionary-itemiterator at 0x2af4470>
In [67]: b = dic.iteritems()
In [68]: b.next()
('gender', 'male')
In [69]: b.next()
('age', 5)
In [70]: b.next()
('name', 'fentiao')
<dictionary-keyiterator at 0x2af4998>
In [73]: c = dic.iterkeys()In [74]: c.next()
'gender'
In [75]: c.next()
'age'
In [76]: c.next()
'name'
{'age': 5, 'gender': 'male', 'name': 'fentiao'}
In [79]: dic.get("age") ##如果key存在于字典中,返回对应value值
5
In [80]: dic.get("name")
'fentiao'
In [81]: dic.has_key("name") ##判断字典中是否存在这个key,存在输出True
True
In [82]: dic.has_key("qwe") ##不存在输出False
False
In [83]: "name" in dic.keys() ##一般情况下最好使用in或not in进行查找
True
{'age': 5, 'gender': 'male', 'name': 'fentiao'}
In [85]: del dic["name"] ##删除字典中name的key及value
In [86]: dic
{'age': 5, 'gender': 'male'}
In [87]: del dic ##删除字典
In [88]: dic
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-88-1b445b6ea935> in <module>()
----> 1 dic
NameError: name 'dic' is not defined
In [90]: dic
{'age': 5, 'gender': 'male', 'name': 'fentiao'}
In [91]: dic.pop("name") ##弹出字典中key值为"name"的元素并返回该key的元素
'fentiao'
In [92]: dic
{'age': 5, 'gender': 'male'}
In [93]: dic.clear() ##删除字典的所有元素
In [94]: dic
{}
In [107]: dic1 = {"name":"fentiao", "kind":"cat", "gender":"male"}
In [108]: dic.update(dic1)
In [109]: dic
{'age': 5, 'gender': 'male', 'kind': 'cat', 'name': 'fentiao'}
In [112]: dic["kind"]= "cat" ##字典中的key-value添加
In [113]: dic["age"] = 2 ##修改age的value值
In [114]: dic
{'age': 2, 'gender': 'male', 'kind': 'cat', 'name': 'fentiao'}
{'age': 2, 'gender': 'male', 'kind': 'cat', 'name': 'fentiao'}
In [116]: dic1 = dic.copy()
In [117]: id(dic)
45299008
In [118]: id(dic1)
45248480
In [119]: dic2 = dic
In [120]: id(dic2)
45299008
注意:
- C语言中,定义一类型,必须先开辟一存储空间,当后期重新赋值时也一定是整型的;
- python中,先在内存上存储数据后,再通过标签去引用。不同的字符串占用不同的存储空间。
In [121]: dic.fromkeys(["a","b","c"])
{'a': None, 'b': None, 'c': None}
In [122]: dic.fromkeys(["a","b","c"],"hello")
{'a': 'hello', 'b': 'hello', 'c': 'hello'}
In [130]: dic.setdefault("kind","cat")
'cat'
In [131]: dic
{'age': 5, 'gender': 'male', 'kind': 'cat', 'name': 'fentiao'}
##去除li中的重复项##
#!/usr/bin/evn python
li = [1,2,3,1,2,3]
d = {}.fromkeys(li)
li = d.keys()
print li
##字典下的四则运算##
#!/usr/bin/evn python
#coding=utf-8
from __future__ import division
a = input("please input first number:")
c = raw_input("operator(+,-,*,/):")
b = input("please input seccond number:")
dic = {"+":a+b, "-":a-b, "*":a*b, "/":a/b}
if c in dic.keys():
print '%s%s%s=%s'%(a,c,b,dic.get(c))
##绝对值##
#!/usr/bin/evn python
#coding=utf-8
a = input("please input a number:")
if not isinstance(a,int):
if a < 0:
a = a*(-1)
print a
else:
print a
else:
print "error type"
while循环:
while expression:
statement(s)
跳出while循环的两种方式:
- 表达式
- 代码块跳出
while中的else语句块:当条件失败正常跳出循环时,执行的代码块
文本处理. 要求输入一个姓名列表,输入格式是“Last Name, First Name,” 即 姓,逗号, 名. 编写程序处理输入, 如果用户输入错误, 比如“First Name Last Name,” , 请纠正这些错误, 并通知用户. 同时你还需要记录输入错误次数. 当用户输入结束后, 给列表排序, 然后以"姓 , 名" 的顺序显示.
#!/usr/bin/evn python
#coding=utf-8
count = input("Enter total number of names:")
a = []
errCount = 0
num = 0
while num < count:
print "Please enter name %d:"%(num+1)
b = raw_input()
if "," in b and ',' != b[0] and b.index(",") != len(b) - 1 and b.count(',') == 1:
a.append(b)
num += 1
else:
errCount += 1
print"Error %d times,Wrong format... should be Last, First."%errCount
print sorted(a)
##continue##
#!/usr/bin/env python
#coding:utf-8
count = 0
while count < 3:
count += 1
a = raw_input("q or c:")
if a == "q":
break ##结束循环
elif a == "c":
continue ##跳出本次循环
elif a == "n":
pass ##不做任何事情,只起到占位的作用
else:
print "error string"
else:
print "else body"
##计算1+2##
#!/usr/bin/env python
#coding:utf-8
def myadd(x,y):
if isinstance(x, (int,float,long)) and isinstance(y,(int,float,long)):
print x + y
else:
print "Error type"
myadd(1,2)
#!/usr/bin/env python
#coding:utf-8
def myadd(x=0,y=0): ##指定默认参数
if isinstance(x, (int,float,long)) and isinstance(y,(int,float,long)):
print x + y
else:
print "Error type"
myadd()
##当没有制定参数时,需要指定默认参数,否则会报错
##局部变量与全局变量##
#!/usr/bin/env python
#coding:utf-8
a = 1 ##此处定义的a为全局变量
def func1():
a = 2
global b ##b为局部变量,因此需要加global变为全局变量
b = 3
print a
func1()
print b
若是不将b定义为全局变量
##传参##
#!/usr/bin/env python
#coding:utf-8
def getInfo(name,age,gender,kind): ##定义一个函数
print name,age,gender,kind
getInfo("fentiao",5,"male","cat") ##传参
#!/usr/bin/env python
#coding:utf-8
def getInfo(name,age,gender,kind):
print name,age,gender,kind
getInfo("fentiao",5,kind="cat",gender="male") ##当传参顺序改变,输出仍然不变,因其用关键字参数指定
顺序改变后,后面所有的参数都需要加关键字参数指定