Python-一些實用的函數


一,返回值為bool類型的函數

1.any()函數

  any(iterable)->bool

  當迭代器中有一個是Ture,則返回Ture;若interable=NUll,則返回False.

>>> any([1,0])
True
>>> any([0,0])
False
>>> any([])
False
>>> any([1,0,0])
True

注:在Python中, False相當於:0,[], (), {}, 0.0 , " ", ' ' .

應用:在一顆二叉樹中,找出每一層中的最大元素(leetcode515)。

Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3,9] 

#類節點的定義
class
node(self) : def __init__(self,data) self.val=data self.right=NULL self.left=NULL

class Solution(object): def largestValues(self, root): maxlist=[] row=[root] while any(row): maxlist.append(max[node.val for node in row]) row=[kid for node in row for kid in node.left,node.right) if kid] return maxlist

2.all()函數

 all(iterable)->bool

 迭代器中每個元素必須都為真時,返回Ture,否則返回False.

>>> all([1,0])
False
>>> all(["e",1])
True

3.isinstance(),issubclass()

1.isinstance(object, classinfo) ->bool.返回True如果參數object是classinfo的一個實例,否則返回False。

2.issubclass(class, classinfo) .返回True如果參數class是classinfo的一個子類,否則返回False。

待續中。。。

二,內置高階函數(可以接受函數名為參數的函數)

    高階函數:在數學中類似於算子,高階導數,復合函數,也就是說把函數當作自變量,通過某種對應關系映射得到一個新的函數。在Python中常見內置的高階函數有:mape(),reduce(),filter(),sortded()

1.map()

     map(function_name,list)->list 。map()將接受 一個函數與列表為參數,返回一個新的列表。這個函數依次對列表中的每個元素進行操作,返回得到的結果,組成一個列表作為輸出的結果。

列如:

def string_len(str):

    return {str[0].upper()+str[1:].lower():len(str)}

strlist=['whb','hello,world','day day up']
print map(string_len,strlist)

>>> [{'Whb': 3}, {'Hello,world': 11}, {'Day day up': 10}]

實現,map()函數的作用相當於迭代,我們只需要定義一個實現我們想要的子結果的函數即可。

2.reduce()

reduce把一個函數f(x,y)作用在一個序列[x1, x2, x3…]上,f(x,y)必須接收兩個參數x,y,reduce把結果繼續和序列的下一個元素做累積計算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

>>> def add(x, y):
...     return x + y
... 
>>> reduce(add, [1, 3, 5, 7, 9])
25

3.filter()

filter(f,list)->list;這個f的作用是對list的每個元素進行判斷,返回True或False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。

def odd(x):
    return x%2!=0
filter(odd,[1,2,3,4,6,3,6,10,3])

filter(f,list)相當於一個篩子,其中f函數就好像就是一個衡量標准,若list中的元素符合標准,就保留下來。否則就刪除掉。

4.sorted()

排序接口:對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本。
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變。

>>> a=[1, 54, 6, 90, 8, 9]
>>> b=[33,7,3,1]
>>> a.sort()
>>> a
[1, 6, 8, 9, 54, 90]
>>> sorted(b)
[1, 3, 7, 33]
>>> b
[33, 7, 3, 1]

 sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

其中

(1)  cmp參數
cmp接受一個函數,拿整形舉例,形式為:
def f(a,b):
     return a-b
如果排序的元素是其他類型的,如果a邏輯小於b,函數返回負數;a邏輯等於b,函數返回0;a邏輯大於b,函數返回正數就行了
(2)  key參數
key參數的值為一個函數,此函數只有一個參數且返回一個值用來進行比較。這個技術是快速的因為 key指定的函數將准確地對每個元素調用。,形式如下
def f(a):
     return len(a)
key接受的函數返回值,表示此元素的權值,sort將按照權值大小進行排序
(3) reverse參數
接受False 或者True 表示是否逆序
 
例如通過key指定的函數來忽略字符串的大小寫:
<<< sorted("This is a test string from Andrew".split(), key=str.lower)
   ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

同樣的技術對擁有命名屬性的復雜對象也適用,例如:

>>> class Student:
        def __init__(self, name, grade, age):
                self.name = name
                self.grade = grade
                self.age = age
        def __repr__(self):
                return repr((self.name, self.grade, self.age))
>>> student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10)]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
sorted里面的key參數的使用非常廣泛,因此python提供了一些方便的函數來使得訪問方法更加容易和快速。operator模塊有itemgetter,attrgetter,從2.6開始還增加了methodcaller方法。使用這些方法,上面的操作將變得更加簡潔和快速:

>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
operator模塊還允許多級的排序,例如,先以grade,然后再以age來排序 >>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

list.sort()sorted()都接受一個參數reverse(True or False)來表示升序或降序排序。

例如對上面的student降序排序如下:

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

待續中。。。

三、類型轉換函數

int("5")                        # 轉換為整數 integer

float(2)                         # 轉換為浮點數 float

long("23")                      # 轉換為長整數 long integer

str(2.3)                        # 轉換為字符串 string

complex(3, 9)                   # 返回復數 3 + 9i

ord("A")                        # "A"字符對應的數值

chr(65)                          # 數值65對應的字符

unichr(65)                       # 數值65對應的unicode字符

bool(0)                          # 轉換為相應的真假值,在Python中,0相當於False

bin(56)                         # 返回一個字符串,表示56的二進制數

hex(56)                         # 返回一個字符串,表示56的十六進制數

oct(56)                         # 返回一個字符串,表示56的八進制數

list((1,2,3))                   # 轉換為表 list

tuple([2,3,4])                  # 轉換為定值表 tuple

slice(5,2,-1)                    # 構建下標對象 slice

dict(a=1,b="hello",c=[1,2,3])   # 構建詞典 dictionary

待續中。。。。

四、字符串處理函數

1、字符串大小寫:

str.capitalize

>>> 'hello'.capitalize()

'Hello'

全部大寫:str.upper()
全部小寫:str.lower()
大小寫互換:str.swapcase()

2、字符串替換

str.replace

>>>'hello'.replace('l','2',1)

'he2lo'

可以傳三個參數,第三個參數為替換次數

3、字符串切割:

str.split

>>> 'hello'.split('l')
['he', '', 'o']

可以傳二個參數,第二個參數為切割次數

4.字符串格式化

獲取固定長度,右對齊,左邊不夠用空格補齊:str.ljust(width)
獲取固定長度,左對齊,右邊不夠用空格補齊:str.rjust(width)
獲取固定長度,中間對齊,兩邊不夠用空格補齊:str.centerjust(width)
獲取固定長度,右對齊,左邊不足用0補齊:str.zfill(width)

>>> str.rjust(40)
'                  python string function'
>>> str.rjust(30,'0')
'00000000python string function'
>>.>str.ljust(30,'0')
'python string function00000000'
>>> str.center(30,'0')
'0000python string function0000'

5.字符串搜索相關
搜索指定字符串,沒有返回-1:str.find('t')
指定起始位置搜索:str.find('t',start)
指定起始及結束位置搜索:str.find('t',start,end)
從右邊開始查找:str.rfind('t')
搜索到多少個指定字符串:str.count('t')
上面所有方法都可用index代替,不同的是使用index查找不到會拋異常,而find返回-1

6.字符串去空格及去指定字符
去兩邊空格:str.strip()
去左空格:str.lstrip()
去右空格:str.rstrip()
去兩邊字符串:str.strip('d'),相應的也有lstrip,rstrip

7.字符串判斷相關
是否以start開頭:str.startswith('start')
是否以end結尾:str.endswith('end')
是否全為字母或數字:str.isalnum()
是否全字母:str.isalpha()
是否全數字:str.isdigit()
是否全小寫:str.islower()
是否全大寫:str.isupper()

 五.其他內置函數

1.enumerate()  .返回一個枚舉類型

>>> for i,j in enumerate(('a','b','c')):
print(i,j)

0 a
1 b
2 c

>>> for i,j in enumerate([1,2,3]):
print(i,j)

0 1
1 2
2 3

>>> for i,j in enumerate('abc'):
print(i,j)

0 a
1 b
2 c

>>> for i,j in enumerate({'a':1,'b':2}):
print(i,j)

0 b
1 a

2.zip(*iterables) 生成一個迭代器,它(迭代器)聚合了從每個可迭代數集里的元素。

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM