12 Python內置函數

  • 本文主要進行講解python內置函數
    主要有以下函數:

help

  • 可以用於查看module,或者函數
# 下面兩行分別爲sys模塊和str類的具體說明。
help('sys')
help('str')

help([1,2,3]) #會詳細說明list的用法
help([1,2,3].append) #會詳細說明list.append()的用法

dict:

  • 可以通過查看dict的用法
class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if D has a key k, else False.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].

通過上面help得到的信息,我們可以通過四種方式進行建立字典,

  • 建立空字典 dict()
  • 通過關鍵字 dict(**kwargs)
  • 傳入映射 dict(mapping)
  • 傳入可迭代對象 dict(iterable)
# 1. 建立空字典 
a = dict()  #空字典
# 2. 通過關鍵字
dictionary = dict(a = '1', b = '2') # {'a': '1', 'b': '2'}
# 3. 通過隱射
a = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # {'a': 1, 'c': 3, 'b': 2}
# 4. 通過傳入可迭代對象
a = dict([('one', 1), ('two', 2), ('three', 3)]) # {'two': 2, 'one': 1, 'three': 3}

zip([iterable, …])

將可迭代的對象進行壓縮成一個對象,可以通過*進行解壓縮

a = [1, 2, 3]
b = [2, 4, 6]
zipped = zip(a, b)
print(zippend)  #<zip object at 0x7f76960880c8>

# 可以通過list進行解壓縮,
list(zipped) # [(1, 2), (2, 4), (3, 6)] 返回一個list

abs:

取絕對值

a = abs(-1) # 1

all:

用於判斷給定的可迭代參數中的所有元素是否全部不爲0, false, None,空
但是值得注意的是,空元組或者是空列表返回的值爲true

all([1, 2, 3]) # True 
all([0, 1, 2]) # false 因爲有個0
all(['a', 'b', '']) # false, 因爲其中有個空 ''

all(()) # true
all([]) # true

dir:

返回模塊中的變量,方法和定義,如果帶參數則返回參數的屬性,方法列表

dir([]) # 返回list的方法列表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章