python不好的地方_Python 语言中经常有疑惑的地方
*)可以這樣,不用保存遞歸中的變量
import os
def findFile (str,dir = os.path.abspath('.')):
for x in os.listdir(dir):
if os.path.isdir(os.path.join(dir,x)):
findFile(str,os.path.join(dir,x))
elif str in x:
print(os.path.join(dir,x))#我一直都是想辦法保存在遞歸的程序中
*)誰說while最少會執(zhí)行一次的,并不是這樣
>>> while a>2:
... print(a)
... a-=1...>>>
>>> a=3
>>> while a>2:
... print(a)
... a-=1...3
View Code
*)append()和extend()的區(qū)別
append()和extend()都只能接受一個參數(shù),但append()能接受不可迭代的或者不可迭代的,但extend只能接受可迭代的(iterable)
>>> a.extend(2,3)
Traceback (most recent call last):
File "", line 1, in
TypeError: extend() takes exactly one argument (2 given)
>>> a.extend(2)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not iterable
append()把參數(shù)添加到一個下標內
>>> a.append(b)
>>> a
[1, 2, 2, 4, [2, 4]]
extend()不是
>>> a=[1,2]
>>> b=[2,4]
>>> a.extend(b)
>>> a
[1, 2, 2, 4]
>>> a.append(b)
>>> a
[1, 2, 2, 4, [2, 4]]
*)方法名相同的情況下,例如方法名內部有重名的方法和參數(shù),調用的情況
def name1(collection):
print('外面的name1,參數(shù):collection:',collection)
def name1(collection):
print('里面的name1,參數(shù):collection:',collection)
name1(collection)
if __name__=='__main__':
collection=[1,2,3,4,5,6]
name1(collection[2:])
(sort) λ python forTest.py
外面的name1,參數(shù):collection: [3, 4, 5, 6]
里面的name1,參數(shù):collection: [3, 4, 5, 6]
*)遞歸失敗:
def name1(collection):
print('外面的name1,參數(shù):collection:',collection)
name1(collection)
Traceback (most recent call last):
File "forTest.py", line 8, in
name1(a)
File "forTest.py", line 5, in name1
name1(collection)
File "forTest.py", line 5, in name1
name1(collection)
File "forTest.py", line 5, in name1
name1(collection)
[Previous line repeated 993 more times]
File "forTest.py", line 2, in name1
print('外面的name1,參數(shù):collection:',collection)
RecursionError: maximum recursion depth exceeded while calling a Python object
*)python中的切片也是[a:b]是從a到b-1的
*)關于for循環(huán)中range(2),i到底是從0還是1開始。特別是在用數(shù)組的長度作為range的參數(shù)的時候經常會犯糊涂
還有range(a,b,c)無論怎樣,返回的數(shù)組都是[a,....b-1](c>0)或者[a,.....b+1](c<0)就是不到b
#首先
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
#其次
>>> s=[1,2,3,4,5]
>>> length=len(s)
>>> for i in range(length):#所以,這里完全不用-1,類似于,因為range()會減去1,這就抵消掉了數(shù)組長度比數(shù)組下標多了1這個屬性說造成的訪問數(shù)組會超出index這個trouble。
... print(s[i])
...
1
2
3
4
5
>>> length
5
*)range反向循環(huán)、反向遞減、將步長設置為負數(shù)就好了,注意要調換開始和結束的位置
>>> for i in range(5,3,-1):#從5開始,到3結束
... print(i)
...
5
4
>>>
*)這樣range(0,0)并不會拋出異常,而是什么也不輸出
>>> for i in range(0,0):
... print(i)
...
>>>
總結
以上是生活随笔為你收集整理的python不好的地方_Python 语言中经常有疑惑的地方的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 5.7.20主从配置_mys
- 下一篇: python做出来的东西_【python