1.print
(1)SyntaxError: invalid syntax
print在python2.7中仅是一个statement,在3.0中才作为一个函数使用
导入print_function既可以解决问题了
(2) IOError: [Errno 9] bad file descriptor
f = open(r'c:\bb.txt')
print >> f, 'we are happy'
IOError: [Errno 9] Bad file descriptor
这个问题主要出在文件打开方式上,open默认的打开文件方式是’r’,现在要把数据写入到文件中,而原文件只是可读的,故需要将文件打开模式变为’w’即可。
2.remove()带来的坑
目的是删除list中的偶数,使用remove()删除之后,报list index out of range的错。原因是:调用remove()后,list的长度变短了,但index的区间还是[0,4]
3.
调用remove后,index改变了。开始的时候是这样的(0,2),(1,4),(2,5),(3,6),(4,8),移除2后,变成了这样(0,4),(1,5),(2,6),(3,8),第二次循环开始时,index=1,故4就被忽略了。remove会改变list的index,小伙伴们要小心了
4.列表进行分片操作的时候,下表超过index的范围的时候,返回一个空的列表
5.
def func(*args):
res = []
for item in args[0]:
for other in args[1:]:
if item in other:
res.append(item)
return res
func([3,45,6,7,23,34],[45,34,67,89,2,3],[78,90,34,23,12,3])
这个函数的目的是找出3个列表中的公共元素,但这个函数的运行结果却不尽人意
原来问题出在这里,for 循环遍历余下的2个列表,3,34在后面两个列表中都出现了,故添加了2次;23,45只存在一个列表中,故只添加一次。这和我们的初衷完全不同啊。怎么来改这个问题呢?
def func(*args):
res = []
for item in args[0]:
for other in args[1:]:
if item not in other: break
else:
res.append(item)
return res
func([3,45,6,7,23,34],[45,34,67,89,2,3],[78,90,34,23,12,3])
这样改就能达到我们的目的了。
6.默认参数和可变对象
def func(value, x=[]):
x.append(value)
return x
因为可变类型的默认参数在函数调用之间保存了它们的状态,从某种意义上讲它们能够充当c语言中的静态本地函数变量的角色
7.类中的运算符重载
def __str__(self):
return “Person: %s %s”%(self.name, self.pay)
函数返回的一个字符串,不然会报错:TypeError: __str__ return non-string
8.
<span style="font-size:18px;">def func(path):
rest = []
fileInfo = {}
for root,dirs,files in os.walk(path):
for item in files:
fileInfo['name'] = os.path.join(root,item)
fileInfo['size'] = os.path.getsize(os.path.join(root,item))
rest.append(fileInfo)
return rest</span>
想得到一个包含文件信息的列表,但rest中的每一项都一样,都是最后一次遍历的文件的. 这样改一下就可以实现我们想要的文件信息列表[{},{},{}]
<span style="font-size:18px;">def func(path):
rest = []
for root,dirs,files in os.walk(path):
for item in files:
fileInfo = {}
fileInfo['name'] = os.path.join(root,item)
fileInfo['size'] = os.path.getsize(os.path.join(root,item))
rest.append(fileInfo)
return rest</span>
9.open
File “F:/pythonPro/pythonPro/io/rw_code.py”, line 8, in rw_mode
with open(‘bb.txt’, param,encoding=’utf-8′) as f:
TypeError: ‘encoding’ is an invalid keyword argument for this function
python2.7不支持encoding这个参数
10.join
>>>'*'.join([1,2,3,4,])
>>>TypeError: sequence item 0:except string, int found
join的参数只能是字符串序列