導讀:Python有很多好用的函數和模塊,這裡給大家整理下我常用的一些方法及語句。
作者:朱衛軍
來源:Python大數據分析
01 內置函數
內置函數是Python自帶的函數方法,拿來就可以用,比方說zip、filter、isinstance等。
下面是Python官檔給出的內置函數列表,相當的齊全。
下面幾個是常見的內置函數:
1. enumerate(iterable,start=0)
enumerate是python的內置函數,是枚舉、列舉的意思。
對於一個可疊代的(iterable)/可遍歷的對象(如列表、字符串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值。
在python中enumerate的用法多用於在for循環中得到計數。
seasons = [ 'Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[( 0, 'Spring'), ( 1, 'Summer'), ( 2, 'Fall'), ( 3, 'Winter')]
list(enumerate(seasons, start= 1))
[( 1, 'Spring'), ( 2, 'Summer'), ( 3, 'Fall'), ( 4, 'Winter')]
2. zip(*iterables,strict=False)
zip 函數用於將可疊代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。
如果各個疊代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。
zip(iterable1,iterable2, ...)
>>> foritem inzip([ 1, 2, 3], [ 'sugar', 'spice', 'everything nice']):
... print(item)
...
( 1, 'sugar')
( 2, 'spice')
( 3, 'everything nice')
3. filter(function,iterable)
filter是將一個序列進行過濾,返回疊代器的對象,去除不滿足條件的序列。
filter(function,data)
function作為條件選擇函數。
比如說定義一個函數來檢查輸入數字是否為偶數。如果數字為偶數,它將返回True,否則返回False。
defis_even(x):
ifx % 2== 0:
returnTrue
else:
returnFalse
然後使用filter對某個列表進行篩選:
l1 = [ 1, 2, 3, 4, 5]
fl = filter(is_even, l1)
list(fl)
4. isinstance(object,classinfo)
「isinstance」是用來判斷某一個變量或者是對象是不是屬於某種類型的一個函數。
如果參數object是classinfo的實例,或者object是classinfo類的子類的一個實例, 返回True。如果object不是一個給定類型的的對象, 則返回結果總是False。
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元組中的一個返回 True
True
5. eval(expression[,globals[,locals]])
eval用來將字符串str當成有效的表達式來求值並返回計算結果。
表達式解析參數expression並作為 Python 表達式進行求值(從技術上說是一個條件列表),採用globals和locals字典作為全局和局部命名空間。
>>>x = 7
>>> eval( '3 * x')
21
>>> eval( 'pow(2,2)')
4
>>> eval( '2 + 2')
4
>>> n= 81
>>> eval( "n + 4")
85
02 常用句式
在日常代碼過程中,其實有很多常用的句式,出現頻率非常高,也是大家約定俗成的寫法。
1. format字符串格式化
format把字符串當成一個模板,通過傳入的參數進行格式化,非常實用且強大。
# 格式化字符串
print( '{} {}'.format( 'hello', 'world'))
# 浮點數
float1 = 563.78453
print( "{:5.2f}".format(float1))
2. 連接字符串
使用+連接兩個字符串。
string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)
3. if...else條件語句
Python 條件語句是通過一條或多條語句的執行結果(True 或者 False)來決定執行的代碼塊。
其中if...else語句用來執行需要判斷的情形。
# Assign a numeric value
number = 70
# Check the is more than 70 or not
if(number >= 70):
print( "You have passed")
else:
print( "You have not passed")
4. for...in、while循環語句
循環語句就是遍歷一個序列,循環去執行某個操作,Python 中的循環語句有 for 和 while。
for循環
for循環
# Initialize the list
weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print( "Seven Weekdays are:\n")
# Iterate the list using for loop
forday inrange(len(weekdays)):
print(weekdays[day])
while循環
while循環
# Initialize counter
counter = 1
# Iterate the loop 5 times
whilecounter < 6:
# Print the counter value
print( "The current counter value: %d"% counter)
# Increment the counter
counter = counter + 1
5. import導入其他腳本的功能
有時需要使用另一個 python 文件中的腳本,這其實很簡單,就像使用 import 關鍵字導入任何模塊一樣。
「vacations.py」
# Initialize values
vacation1 = "Summer Vacation"
vacation2 = "Winter Vacation"
比如在下面腳本中去引用上面vacations.py中的代碼。
# Import another python
importvacations asv
# Initialize the month list
months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
# Initial flag variable to print summer vacation one time
flag = 0
# Iterate the list using for loop
formonth inmonths:
ifmonth == "June"ormonth == "July":
ifflag == 0:
print( "Now",v.vacation1)
flag = 1
elifmonth == "December":
print( "Now",v.vacation2)
else:
print( "The current month is",month)
6. 列表推導式
Python 列表推導式是從一個或者多個疊代器快速簡潔地創建數據類型的一種方法,它將循環和條件判斷結合,從而避免語法冗長的代碼,提高代碼運行效率。能熟練使用推導式也可以間接說明你已經超越了 Python 初學者的水平。
# Create a list of characters using list comprehension
char_list = [ char forchar in"linuxhint"]
print(char_list)
# Define a tuple of websites
websites = ( "google.com", "yahoo.com", "ask.com", "bing.com")
# Create a list from tuple using list comprehension
site_list = [ site forsite inwebsites ]
print(site_list)
7. 讀寫文件
與計算的交互式Python最常使用的場景之一,比如去讀取D盤中CSV文件,然後重新寫入數據再保存。這就需要python執行讀寫文件的操作,這也是初學者要掌握的核心技能。
#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")
# Add some text
fileHandler.write( "Bash\n")
fileHandler.write( "Python\n")
fileHandler.write( "PHP\n")
# Close the file
fileHandler.close
# Open file for reading
fileHandler = open(filename, "r")
# Read a file line by line
forline infileHandler:
print(line)
# Close the file
fileHandler.close
8. 切片和索引
形如列表、字符串、元組等序列,都有切片和索引的需求,因為我們需要從中截取數據,所以這也是非常核心的技能。
var1 = 'Hello World!'
var2 = "zhihu"
print( "var1[0]: ", var1[ 0])
print( "var2[1:5]: ", var2[ 1: 5])
9. 使用函數和類
函數和類是一種封裝好的代碼塊,可以讓代碼更加簡潔、實用、高效、強壯,是python的核心語法之一。
定義和調用函數
定義和調用函數
# Define addition function
defaddition(number1, number2):
result = number1 + number2
print( "Addition result:",result)
# Define area function with return statement
defarea(radius):
result = 3.14* radius * radius
returnresult
# Call addition function
addition( 400, 300)
# Call area function
print( "Area of the circle is",area( 4))
定義和實例化類
定義和實例化類
# Define the class
classEmployee:
name = "Mostak Mahmud"
# Define the method
defdetails(self):
print( "Post: Marketing Officer")
print( "Department: Sales")
print( "Salary: $1000")
# Create the employee object
emp = Employee
# Print the class variable
print( "Name:",emp.name)
# Call the class method
emp.details
10. 錯誤異常處理
編程過程中難免會遇到錯誤和異常,所以我們要及時處理它,避免對後續代碼造成影響。
所有的標準異常都使用類來實現,都是基類Exception的成員,都從基類Exception繼承,而且都在exceptions模塊中定義。
Python自動將所有異常名稱放在內建命名空間中,所以程序不必導入exceptions模塊即可使用異常。一旦引發而且沒有捕捉SystemExit異常,程序執行就會終止。
異常的處理過程、如何引發或拋出異常及如何構建自己的異常類都是需要深入理解的。
# Try block
try:
# Take a number
number = int(input( "Enter a number: "))
ifnumber % 2== 0:
print( "Number is even")
else:
print( "Number is odd")
# Exception block
except(ValueError):
# Print error message
print( "Enter a numeric value")
小結
當然Python還有很多有用的函數和方法,需要大家自己去總結,這裡拋磚引玉,希望能幫助到需要的小夥伴。
點這裡關注我,記得標星哦~
CDA課程諮詢