Python最常用的函数、基础语句有哪些?
一、内置函数
内置函数是python自带的函数方法,拿来就可以用,比方说zip、filter、isinstance等。
下面是Python官档给出的内置函数列表,相当的齐全。
下面几个是常见的内置函数:
1、<code style="font-family: monospace; font-size: inherit; background-color: rgba(0, 0, 0, 0.06); padding: 0px 2px; border-radius: 6px; line-height: inherit; overflow-wrap: break-word; text-indent: 0px;"><span style="font-size: 18px;">enumerate</span>
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、<span style="font-size: 18px;">zip</span>
<span style="font-size: 18px;">zip</span>
(*iterables,strict=False)>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
<span style="font-size: 18px;">filter</span>
3、</span>filter</h3>
(function,iterable)
def is_even(x):
if x % 2 == 0:
return True
else:
return False
登录后复制filter是将一个序列进行过滤,返回迭代器的对象,去除不满足条件的序列。filter(function,data)function作为条件选择函数比如说定义一个函数来检查输入数字是否为偶数。如果数字为偶数,它将返回True,否则返回False。
l1 = [1, 2, 3, 4, 5]
fl = filter(is_even, l1)
list(fl)
登录后复制然后使用filter对某个列表进行筛选:<span style="font-size: 18px;">isinstance</span>
4、</h3>isinstance<p >
(object,classinfo)
「isinstance」>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True
登录后复制是用来判断某一个变量或者是对象是不是属于某种类型的一个函数如果参数object是classinfo的实例,或者object是classinfo类的子类的一个实例, 返回True。如果object不是一个给定类型的的对象, 则返回结果总是False<span style="font-size: 18px;">eval</span>
5、
<p >eval</p>
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
登录后复制(expression[,globals[,locals]])eval用来将字符串str当成有效的表达式来求值并返回计算结果表达式解析参数expression并作为 Python 表达式进行求值(从技术上说是一个条件列表),采用globals和locals字典作为全局和局部命名空间。
常用句式
在日常代码过程中,其实有很多常用的句式,出现频率非常高,也是大家约定俗成的写法。
1、format字符串格式化# 格式化字符串
print('{} {}'.format('hello','world'))
# 浮点数
float1 = 563.78453
print("{:5.2f}".format(float1))
登录后复制format把字符串当成一个模板,通过传入的参数进行格式化,非常实用且强大
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("Bashn")
fileHandler.write("Pythonn")
fileHandler.write("PHPn")
# 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还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。
以上是Python最常用的函数、基础语句有哪些?的详细内容。更多信息请关注PHP中文网其他相关文章!
def is_even(x): if x % 2 == 0: return True else: return False
l1 = [1, 2, 3, 4, 5] fl = filter(is_even, l1) list(fl)
<span style="font-size: 18px;">isinstance</span>
4、</h3>isinstance<p >
(object,classinfo)>>>a = 2 >>> isinstance (a,int) True >>> isinstance (a,str) False >>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True True
<span style="font-size: 18px;">eval</span>
5、>>>x = 7 >>> eval( '3 * x' ) 21 >>> eval('pow(2,2)') 4 >>> eval('2 + 2') 4 >>> n=81 >>> eval("n + 4") 85
# 格式化字符串 print('{} {}'.format('hello','world')) # 浮点数 float1 = 563.78453 print("{:5.2f}".format(float1))
string1 = "Linux" string2 = "Hint" joined_string = string1 + string2 print(joined_string)
# 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")
# 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])
# 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
# Initialize values vacation1 = "Summer Vacation" vacation2 = "Winter Vacation"
# 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)
# 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)
#Assign the filename filename = "languages.txt" # Open file for writing fileHandler = open(filename, "w") # Add some text fileHandler.write("Bashn") fileHandler.write("Pythonn") fileHandler.write("PHPn") # 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()

var1 = 'Hello World!' var2 = "zhihu" print ("var1[0]: ", var1[0]) print ("var2[1:5]: ", var2[1:5])
# 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()
# 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")

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

MySQL 有免费的社区版和收费的企业版。社区版可免费使用和修改,但支持有限,适合稳定性要求不高、技术能力强的应用。企业版提供全面商业支持,适合需要稳定可靠、高性能数据库且愿意为支持买单的应用。选择版本时考虑的因素包括应用关键性、预算和技术技能。没有完美的选项,只有最合适的方案,需根据具体情况谨慎选择。

文章介绍了MySQL数据库的上手操作。首先,需安装MySQL客户端,如MySQLWorkbench或命令行客户端。1.使用mysql-uroot-p命令连接服务器,并使用root账户密码登录;2.使用CREATEDATABASE创建数据库,USE选择数据库;3.使用CREATETABLE创建表,定义字段及数据类型;4.使用INSERTINTO插入数据,SELECT查询数据,UPDATE更新数据,DELETE删除数据。熟练掌握这些步骤,并学习处理常见问题和优化数据库性能,才能高效使用MySQL。

MySQL安装失败的原因主要有:1.权限问题,需以管理员身份运行或使用sudo命令;2.依赖项缺失,需安装相关开发包;3.端口冲突,需关闭占用3306端口的程序或修改配置文件;4.安装包损坏,需重新下载并验证完整性;5.环境变量配置错误,需根据操作系统正确配置环境变量。解决这些问题,仔细检查每个步骤,就能顺利安装MySQL。

MySQL下载文件损坏,咋整?哎,下载个MySQL都能遇到文件损坏,这年头真是不容易啊!这篇文章就来聊聊怎么解决这个问题,让大家少走弯路。读完之后,你不仅能修复损坏的MySQL安装包,还能对下载和安装过程有更深入的理解,避免以后再踩坑。先说说为啥下载文件会损坏这原因可多了去了,网络问题是罪魁祸首,下载过程中断、网络不稳定都可能导致文件损坏。还有就是下载源本身的问题,服务器文件本身就坏了,你下载下来当然也是坏的。另外,一些杀毒软件过度“热情”的扫描也可能造成文件损坏。诊断问题:确定文件是否真的损坏

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

MySQL 可在无需网络连接的情况下运行,进行基本的数据存储和管理。但是,对于与其他系统交互、远程访问或使用高级功能(如复制和集群)的情况,则需要网络连接。此外,安全措施(如防火墙)、性能优化(选择合适的网络连接)和数据备份对于连接到互联网的 MySQL 数据库至关重要。

MySQL性能优化需从安装配置、索引及查询优化、监控与调优三个方面入手。1.安装后需根据服务器配置调整my.cnf文件,例如innodb_buffer_pool_size参数,并关闭query_cache_size;2.创建合适的索引,避免索引过多,并优化查询语句,例如使用EXPLAIN命令分析执行计划;3.利用MySQL自带监控工具(SHOWPROCESSLIST,SHOWSTATUS)监控数据库运行状况,定期备份和整理数据库。通过这些步骤,持续优化,才能提升MySQL数据库性能。

MySQL数据库性能优化指南在资源密集型应用中,MySQL数据库扮演着至关重要的角色,负责管理海量事务。然而,随着应用规模的扩大,数据库性能瓶颈往往成为制约因素。本文将探讨一系列行之有效的MySQL性能优化策略,确保您的应用在高负载下依然保持高效响应。我们将结合实际案例,深入讲解索引、查询优化、数据库设计以及缓存等关键技术。1.数据库架构设计优化合理的数据库架构是MySQL性能优化的基石。以下是一些核心原则:选择合适的数据类型选择最小的、符合需求的数据类型,既能节省存储空间,又能提升数据处理速度
