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 表达式举行求值(从技能上说是一个条件列表),采取globals和locals字典作为全局和局部定名空间。
- >>>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尚有很多有效的函数和方法,须要各人本身去总结,这里抛砖引玉,盼望能资助到须要的小同伴。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金 |