Python常用函数和语句

Python有很多好用的函数和模块,这里给大家整理下我常用的一些方法及语句。

一、内置函数

内置函数是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, ...)

>>> for item in zip([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。

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

然后使用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 表达式进行求值(从技术上说是一个条件列表),采用globalslocals字典作为全局和局部命名空间。

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85

常用句式

在日常代码过程中,其实有很多常用的句式,出现频率非常高,也是大家约定俗成的写法。

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循环

# Initialize the list
weekdays = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday","Friday", "Saturday"]
print("Seven Weekdays are:\n")
# Iterate the list using for loop
for day in range(len(weekdays)):
    print(weekdays[day])

while循环

# Initialize counter
counter = 1
# Iterate the loop 5 times
while counter < 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 script
import vacations as v

# 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
for month in months:
    if month == "June" or month == "July":
        if flag == 0:
            print("Now",v.vacation1)
            flag = 1
    elif month == "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 for char 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 for site in websites ]
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
for line in fileHandler:
  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
def addition(number1, number2):
    result = number1 + number2
    print("Addition result:",result)

# Define area function with return statement
def area(radius):
    result = 3.14 * radius * radius
    return result  

# Call addition function
addition(400, 300)
# Call area function
print("Area of the circle is",area(4))

定义和实例化类

# Define the class
class Employee:
    name = "Mostak Mahmud"
    # Define the method
    def details(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: "))
    if number % 2 == 0:
        print("Number is even")
    else:
        print("Number is odd")

# Exception block    
except (ValueError):
  # Print error message
  print("Enter a numeric value")

小结

当然Python还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • Remove time complexity: remove from a set is O(1), remove...
    云端漫步_b5aa阅读 607评论 0 0
  • Python语言特性 1 Python的函数参数传递 看两个如下例子,分析运行结果: 代码一: a = 1 def...
    伊森H阅读 3,024评论 0 15
  • Python语言特性 1 Python的函数参数传递 看两个如下例子,分析运行结果: 代码一: a = 1 def...
    时光清浅03阅读 463评论 0 0
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 2,708评论 0 8
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,203评论 4 16