**====>用isinstance([],list) 来判断是否为列表类型或者type([]) is list【is 结合type使用】
In [65]: content
Out[65]: {'black': {'age': 22, 'phone': 99999}, 'colo': ['22222', 60], 'name': 'xiugai'}
In [64]: for k ,v in content.items():
...: print '%s : ----------' %k
...: if isinstance(v,dict):
...: for i ,j in v.items():
...: print i ,j
...: elif type(v) is list :
...: for x in [x for x in v]:
...: print x
...: print v
...:
colo : ----------
22222
60
['22222', 60]
black : ----------
phone 99999
age 22
{'phone': 99999, 'age': 22}
name : ----------
xiugai
####判断是否为字符串str,生产中isinstence使用的多
In [70]: res = isinstance("hello",str)
In [71]: res
Out[71]: True
4.4 字典生成式:字典的高级用法(可以快速翻转字典)
格式:
dict( (v,k) for k ,v in d.iteritems())
dict( [(v,k) for k ,v in d.iteritems() ] )
###字典生成式小例子
In [37]: d = {1:2,3:4,5:6,7:8}
In [38]: print dict( (k ,v) for k ,v in d.iteritems())
{1: 2, 3: 4, 5: 6, 7: 8}
In [39]: print dict( (v ,k) for k ,v in d.iteritems())
{8: 7, 2: 1, 4: 3, 6: 5}
说明:
1.在Python2.6或更早的版本,字典生成器可以接受迭代的键/值对:
d = dict((key,value) for (key,value) in iterable) #第一个key,value的()必须写,第二个可以不写
2.从Python2.7或者3以后,可以直接用字典推导式语法:
d = { key:value for (key,value) in interable} #key,value的()可以不写
##python2.6版本
In [39]: print dict( (v ,k) for k ,v in d.iteritems())
{8: 7, 2: 1, 4: 3, 6: 5}
#python2.7及其以上版本
In [40]: {v : k for k ,v in d.items()}
Out[40]: {2: 1, 4: 3, 6: 5, 8: 7}
##拼接的高阶用法===>生产环境中查询多条数据返回的结果
In [41]: res = [{'id':1,'name':'wd','age':18},{'id':2,'name':'test','age':2
...: 8}]
In [44]: dict((str(x['id']),x['name']) for x in res)
Out[44]: {'1': 'wd', '2': 'test'}
4.5 字典小例子:
4.5.1 将字符串中每个出现的单子个数统计出来
The cafeteria was noisy , but silence hung between us . Valeri didn't seem to mind , but it drove me crazy . I searched my mind for things to say .
####具体代码如下:
In [8]: sentence = "I am Bob ! I am a boy ."
In [9]: arr = sentence.split(" ")
In [10]: res_dict = {}
In [11]: for i in arr:
...: res_dict[i] = res_dict.get(i,0) + 1 ===>高阶代码,可以省略四行代码
###统计出来单词及其对应的个数
In [12]: res_dict
Out[12]: {'!': 1, '.': 1, 'Bob': 1, 'I': 2, 'a': 1, 'am': 2, 'boy': 1}
###具体代码如下:
In [25]: new = {}
In [26]: for k ,v in res_dict.items():
...: if v not in new.keys():
...: new[v] = [k]
...: else :
...: new[v].append(k)
In [27]: print new
{1: ['!', 'a', 'boy', '.', 'Bob'], 2: ['I', 'am']}
###使用setdefault()函数优化代码
In [30]: for k ,v in res_dict.items():
...: new.setdefault(v,[])
...: new[v].append(k)
...:
In [31]: new
Out[31]: {1: ['!', 'a', 'boy', '.', 'Bob'], 2: ['I', 'am']}
五、字符串的基础知识
In [45]: name = "hello"
In [46]: name.startswith('h')
Out[46]: True
In [47]: name.startswith('H')
Out[47]: False
##字符串的格式化 C的风格和 C#风格
In [48]: print "hello %s " % "xx" ##C风格
hello xx
In [49]: print "hello {}" .format("wd")###C#风格
hello wd
In [50]: print "hello {1} {0}" .format("How are you","wd")###C#风格的优势可以更改格式化的顺序
hello wd How are you
列表的格式化:
list = ['hello', '1', '7']
'%s %d-%d' % ('hello', 1, 7)
'%s %s-%s' % (list[0],list[1],list[2])
高逼格:推荐生产中使用
'%s' %' ' .join(list)
字典的格式化:
In [60]: d = {'name':'aa' ,'age':13}
In [61]: "i am %(name)s ,my age is %(age)s" %(d)
Out[61]: 'i am aa ,my age is 13'
In [63]: "i am {name} ,my age is {age}" .format(**d) ##字典两个*号,列表一个*
Out[63]: 'i am aa ,my age is 13'
####strip函数===>主要用于查找以.py等特定后缀结尾的文件名
In [64]: st = " aa "
In [65]: st.lstrip()
Out[65]: 'aa '
In [66]: st.rstrip()
Out[66]: ' aa'
In [67]: st.strip()
Out[67]: 'aa'
##查找以.py等特定后缀结尾的文件名
In [68]: a = 'test.py'
In [69]: a.rstrip(".py")
Out[69]: 'test'
5.1 小练习:##查找以.py等特定后缀结尾的文件名
In [79]: result = []
In [80]: for filename in os.listdir('/usr/local/src/python/03'):
...: if filename.endswith(".py"):
...: result.append(filename.rstrip('.py'))
...: print result
['dict_turn', '01']
六、文件的操作
文件打开分为三步: 打开文件==>读文件==>关闭文件
文件的主要内容也是增删改查
In [81]: f = open('/usr/local/src/python/03/01.py')
In [82]: f.read()
Out[82]: "l = ['hello',1,3]\nprint ','.join(l)\n"
In [83]: f.close()
###运维的职责主要是读文件筛查日志
###增加 write 新增一行
###writelines 新增多行
##查 read readlines
###字符串、列表、字典文件的相互转换
6.1 文件打开的两种方式
方法一:f = open() 这种方法必须关闭文件,否则会报错
方法二:with open() as f: 这个方法代码简洁。会自行关闭文件
###代码举例
###方法一代码举例
In [2]: f = open("01.py")
In [3]: print f.read()
l = ['hello',1,3]
print ','.join(l)
In [4]: f.close()
###方法二代码举例
In [5]: with open('01.py') as f1:
...: print f1.read()
...:
l = ['hello',1,3]
print ','.join(l)
七、结合文件读写实现简单的用户注册登陆系统
7.1 ##用户注册:
代码如下:
f = open("users.txt","a+")
#f.write("wd:123\n")
#mes = ["kk:321\n","ss:456\n"]
#f.writelines(mes) ###可以直接将列表中的元素写到文件中去
while True:
name = raw_input("Please input you name :").rstrip()
passwd = raw_input("Please input you password: ")
repass = raw_input("Please confirm you password: ")
if len(name) == 0:
print "Name can't NULL,Input name again"
continue
if( passwd != repass) or (len(passwd) == 0) or (len(repass) == 0):
print "Password Wrong"
else :
tmp = ["%s:%s\n" %(name,passwd)]
f.writelines(tmp)
#print "tmp is %s" %tmp
print " OK "
break
f.close()
7.2 ####用户登陆
####登录代码:
#/usr/bin/python
import sys
f = open('users.txt','r')
tlist = []
for i in f.readlines():
print i.strip('\n')
t = i.strip('\n').split(":")
tlist.append(t)
print tlist
res = dict((x[0],x[1]) for x in tlist)
print res
f.close()
####login Module
while True :
name = raw_input("Please input The username : ")
if name not in res.keys():
print "The user is not exists"
sys.exit(6)
time = 1
while time < 4:
pword = raw_input("Please input the password %s times :" %time)
if ( len(pword) == 0 ) or pword != res[name]:
print "The password is Wrong"
else:
print "login Sucess"
sys.exit(0)
if time == 3:
sys.exit("三次密码输入错误,请联系管理员解锁")
time += 1
web.xml报错
The content of element type "web-app" must match "(icon?,display-
name?,description?,distributable?,context-param*,filter*,filter-mapping*,listener*,servlet*,s
JUnit4:Test文档中的解释:
The Test annotation supports two optional parameters.
The first, expected, declares that a test method should throw an exception.
If it doesn't throw an exception or if it
借鉴网上的思路,用java实现:
public class NoIfWhile {
/**
* @param args
*
* find x=1+2+3+....n
*/
public static void main(String[] args) {
int n=10;
int re=find(n);
System.o
在Linux中执行.sh脚本,异常/bin/sh^M: bad interpreter: No such file or directory。
分析:这是不同系统编码格式引起的:在windows系统中编辑的.sh文件可能有不可见字符,所以在Linux系统下执行会报以上异常信息。
解决:
1)在windows下转换:
利用一些编辑器如UltraEdit或EditPlus等工具
Binary search tree works well for a wide variety of applications, but they have poor worst-case performance. Now we introduce a type of binary search tree where costs are guaranteed to be loga