Heim  >  Artikel  >  Backend-Entwicklung  >  Was sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?

Was sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?

PHPz
PHPznach vorne
2023-04-11 16:43:031636Durchsuche

Was sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?

1. Eingebaute Funktionen

Eingebaute Funktionen sind Python-eigene Funktionsmethoden, die sofort verwendet werden können, wie z. B. zip, filter, isinstance usw.

Das Folgende ist eine Liste der integrierten Funktionen in der offiziellen Python-Dokumentation, die ziemlich vollständig ist.

Was sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?

Die folgenden sind häufig integrierte Funktionen:

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>​​(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>(*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、​<span style="font-size: 18px;">​filter​</span>(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、<span style="font-size: 18px;">​isinstance​</span>​(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、​​<span style="font-size: 18px;">eval</span>​enumerate​​ (iterable,start=0)

enumerate() ist die in Python integrierte Funktion, die Aufzählung bedeutet. Für ein iterierbares/durchquerbares Objekt (z. B. eine Liste, eine Zeichenfolge) bildet enumerate eine Indexsequenz, die verwendet werden kann um den Index und den Wert gleichzeitig zu erhalten. Die Verwendung von enumerate in Python wird hauptsächlich verwendet, um die Anzahl in der for-Schleife zu erhalten. Größe: erben; Hintergrundfarbe: 0px 2px; Zeilenhöhe: erben; Texteinzug: 0px; " >

​zip​

(*iterables,strict=False)

zip()-Funktion wird verwendet, um ein iterierbares Objekt als Parameter zu nehmen, die entsprechenden Elemente im Objekt in Tupel zu packen und dann Gibt eine Liste zurück, die aus diesen Tupeln besteht. Wenn die Anzahl der Elemente in jedem Iterator inkonsistent ist, entspricht die Länge der zurückgegebenen Liste der des kürzesten Objekts. Das Tupel kann mit dem *-Operator in eine Liste dekomprimiert werden. zip(iterable1,iterable2, ...)

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

3、​

<span style="font-size: 18px;">​filter​<strong></strong></span>

filter filtert eine Sequenz, gibt ein Iteratorobjekt zurück und entfernt Sequenzen, die die Bedingungen nicht erfüllen. Die Funktion filter(function,data) dient als bedingte Auswahlfunktion und definiert beispielsweise eine Funktion, um zu prüfen, ob die eingegebene Zahl eine gerade Zahl ist. Es wird „True“ zurückgegeben, wenn die Zahl gerade ist, andernfalls wird „False“ zurückgegeben.

# 格式化字符串
print('{} {}'.format('hello','world')) 

# 浮点数
float1 = 563.78453
print("{:5.2f}".format(float1))

Dann verwenden Sie den Filter, um eine Liste zu filtern:

string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)

4, ​isinstance​

​(object, classinfo)

🎜"isinstance"🎜 ist eine Funktion, die verwendet wird, um zu bestimmen, ob eine Variable oder ein Objekt zu einem bestimmten Typ gehört. 🎜🎜Wenn das Parameterobjekt eine Instanz von classinfo ist oder das Objekt eine Instanz einer Unterklasse der classinfo-Klasse ist, wird zurückgegeben WAHR. Wenn das Objekt kein Objekt eines bestimmten Typs ist, ist das Rückgabeergebnis immer False🎜
# 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")

🎜🎜5,​🎜​​🎜eval🎜​ ​🎜​(expression[,globals[,locals]])🎜🎜🎜eval wird verwendet, um die Zeichenfolge str als gültigen Ausdruck auszuwerten und das Berechnungsergebnis zurückzugeben. Der Ausdruck analysiert den Parameterausdruck und wertet ihn als Python-Ausdruck aus ( Technisch gesehen eine Liste von Bedingungen), wobei die Wörterbücher globals und locals als globale und lokale Namespaces verwendet werden. 🎜<pre class="brush:python;toolbar:false;"># Initialize the list weekdays = [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;,&quot;Wednesday&quot;, &quot;Thursday&quot;,&quot;Friday&quot;, &quot;Saturday&quot;] print(&quot;Seven Weekdays are:n&quot;) # Iterate the list using for loop for day in range(len(weekdays)): print(weekdays[day]) </pre>🎜🎜Häufig verwendete Satzmuster🎜🎜🎜🎜Im täglichen Codierungsprozess gibt es tatsächlich viele häufig verwendete Satzmuster, die sehr häufig vorkommen und auch gängige Schreibmethoden sind. 🎜🎜🎜🎜🎜1. Formatierung von Zeichenfolgen🎜🎜🎜🎜Format behandelt die Zeichenfolge als Vorlage und formatiert sie über die übergebenen Parameter + um zwei Zeichenfolgen zu verketten🎜🎜<pre class="brush:python;toolbar:false;">string1 = &quot;Linux&quot; string2 = &quot;Hint&quot; joined_string = string1 + string2 print(joined_string) </pre><h3><span style="font-size: 18px;"><strong>3、if...else条件语句</strong></span></h3> <p>Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。其中if...else语句用来执行需要判断的情形。</p><pre class="brush:python;toolbar:false;"># Assign a numeric value number = 70 # Check the is more than 70 or not if (number &gt;= 70): print(&quot;You have passed&quot;) else: print(&quot;You have not passed&quot;) </pre><h3><span style="font-size: 18px;"><strong>4、for...in、while循环语句</strong></span></h3> <p>循环语句就是遍历一个序列,循环去执行某个操作,Python 中的循环语句有 for 和 while。for循环</p><pre class="brush:python;toolbar:false;"># Initialize the list weekdays = [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;,&quot;Wednesday&quot;, &quot;Thursday&quot;,&quot;Friday&quot;, &quot;Saturday&quot;] print(&quot;Seven Weekdays are:n&quot;) # Iterate the list using for loop for day in range(len(weekdays)): print(weekdays[day]) </pre><p>while循环</p><pre class="brush:python;toolbar:false;"># Initialize counter counter = 1 # Iterate the loop 5 times while counter &lt; 6: # Print the counter value print (&quot;The current counter value: %d&quot; % counter) # Increment the counter counter = counter + 1 </pre><h3><span style="font-size: 18px;"><strong>5、import导入其他脚本的功能</strong></span></h3> <p>有时需要使用另一个 python 文件中的脚本,这其实很简单,就像使用 import 关键字导入任何模块一样。<strong>「vacations.py」</strong></p><pre class="brush:python;toolbar:false;"># Initialize values vacation1 = &quot;Summer Vacation&quot; vacation2 = &quot;Winter Vacation&quot; </pre><p>比如在下面脚本中去引用上面vacations.py中的代码</p><pre class="brush:python;toolbar:false;"># Import another python script import vacations as v # Initialize the month list months = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;] # Initial flag variable to print summer vacation one time flag = 0 # Iterate the list using for loop for month in months: if month == &quot;June&quot; or month == &quot;July&quot;: if flag == 0: print(&quot;Now&quot;,v.vacation1) flag = 1 elif month == &quot;December&quot;: print(&quot;Now&quot;,v.vacation2) else: print(&quot;The current month is&quot;,month) </pre><h3><span style="font-size: 18px;"><strong>6、列表推导式</strong></span></h3> <p>Python 列表推导式是从一个或者多个迭代器快速简洁地创建数据类型的一种方法,它将循环和条件判断结合,从而避免语法冗长的代码,提高代码运行效率。能熟练使用推导式也可以间接说明你已经超越了 Python 初学者的水平。</p><pre class="brush:python;toolbar:false;"># Create a list of characters using list comprehension char_list = [ char for char in &quot;linuxhint&quot; ] print(char_list) # Define a tuple of websites websites = (&quot;google.com&quot;,&quot;yahoo.com&quot;, &quot;ask.com&quot;, &quot;bing.com&quot;) # Create a list from tuple using list comprehension site_list = [ site for site in websites ] print(site_list) </pre><h3><span style="font-size: 18px;"><strong>7、读写文件</strong></span></h3> <p>与计算的交互式Python最常使用的场景之一,比如去读取D盘中CSV文件,然后重新写入数据再保存。这就需要python执行读写文件的操作,这也是初学者要掌握的核心技能。</p><pre class="brush:python;toolbar:false;">#Assign the filename filename = &quot;languages.txt&quot; # Open file for writing fileHandler = open(filename, &quot;w&quot;) # Add some text fileHandler.write(&quot;Bashn&quot;) fileHandler.write(&quot;Pythonn&quot;) fileHandler.write(&quot;PHPn&quot;) # Close the file fileHandler.close() # Open file for reading fileHandler = open(filename, &quot;r&quot;) # Read a file line by line for line in fileHandler: print(line) # Close the file fileHandler.close() </pre><h3><span style="font-size: 18px;"><strong>8、切片和索引</strong></span></h3> <p><span style="font-size: 15px;">形如列表、字符串、元组等序列,都有切片和索引的需求,因为我们需要从中截取数据,所以这也是非常核心的技能。</span></p> <p style="text-align: center;"><img src="https://img.php.cn/upload/article/000/000/164/168120258542251.png" data-type="inline" style="max-width:90%" alt="Was sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?" ></p><pre class="brush:python;toolbar:false;">var1 = 'Hello World!' var2 = &quot;zhihu&quot; print (&quot;var1[0]: &quot;, var1[0]) print (&quot;var2[1:5]: &quot;, var2[1:5]) </pre><h3><span style="font-size: 18px;"><strong>9、使用函数和类</strong></span></h3> <p>函数和类是一种封装好的代码块,可以让代码更加简洁、实用、高效、强壮,是python的核心语法之一。定义和调用函数</p><pre class="brush:python;toolbar:false;"># Define addition function def addition(number1, number2): result = number1 + number2 print(&quot;Addition result:&quot;,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(&quot;Area of the circle is&quot;,area(4)) </pre><p>定义和实例化类</p><pre class="brush:python;toolbar:false;"># Define the class class Employee: name = &quot;Mostak Mahmud&quot; # Define the method def details(self): print(&quot;Post: Marketing Officer&quot;) print(&quot;Department: Sales&quot;) print(&quot;Salary: $1000&quot;) # Create the employee object emp = Employee() # Print the class variable print(&quot;Name:&quot;,emp.name) # Call the class method emp.details() </pre><h3><span style="font-size: 18px;"><strong>10、错误异常处理</strong></span></h3> <p>编程过程中难免会遇到错误和异常,所以我们要及时处理它,避免对后续代码造成影响。所有的标准异常都使用类来实现,都是基类Exception的成员,都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。异常的处理过程、如何引发或抛出异常及如何构建自己的异常类都是需要深入理解的。</p><pre class="brush:python;toolbar:false;"># Try block try: # Take a number number = int(input(&quot;Enter a number: &quot;)) if number % 2 == 0: print(&quot;Number is even&quot;) else: print(&quot;Number is odd&quot;) # Exception block except (ValueError): # Print error message print(&quot;Enter a numeric value&quot;) </pre><h3><span style="font-size: 18px;">小结</span></h3> <p>当然Python还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。</p>

Das obige ist der detaillierte Inhalt vonWas sind die am häufigsten verwendeten Funktionen und Grundanweisungen in Python?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:51cto.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen