程式設計師的 Python 基本提示和技巧?
我們將涵蓋一些有用的 python 技巧和提示,這些技巧和提示在為競爭性程式設計或為公司編寫程式時非常有用,因為它們可以減少程式碼和最佳化執行。
使用模組 heapq 獲取列表中的 n 個最大元素
示例
import heapq
marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66]
print("Marks = ",marks)
print("Largest =",heapq.nlargest(2, marks))
輸出
Marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] Largest = [99, 91]
使用模組 heapq 獲取列表中 n 個最小元素
示例
import heapq
marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66]
print("Marks = ",marks)
print("Smallest =",heapq.nsmallest(2, marks))
輸出
Marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] Smallest = [23, 34]
從列表建立一個字串
示例
myList = ['Hello', 'World']
print(" ".join(myList))
輸出
Hello World
在一行中分配多個變數
示例
a, b, c = 10, 20, 30 print(a, b, c)
輸出
10 20 30
在一行中迴圈列表中的元素:列表解析
示例
myList = [5, 12, 15, 18, 24, 32, 55, 65]
res = [number for number in myList if number % 5 == 0]
print("Displaying numbers divisible by 5 = ",res)
輸出
Displaying numbers divisible by 5 = [5, 15, 55, 65]
兩個數字的原地交換
示例
a, b = 50, 70
print("Before Swapping = ",a, b)
# swapping
a, b = b, a
print("After Swapping = ",a, b)
輸出
Before Swapping = 50 70 After Swapping = 70 50
在一行中反轉字串
示例
# Reverse a string
myStr = "This is it!!!"
print("String = ",myStr)
print("Reversed String = ",myStr[::-1])
輸出
String = This is it!!! Reversed String = !!!ti si sihT
從兩個相關序列建立字典
示例
# Creating a dictionary from two related sequences
s1 = ('Name', 'EmpId', 'Dept')
r1 = ('Jones', 767, 'Marketing')
print(dict (zip(s1, r1)))
輸出
{'Name': 'Jones', 'EmpId': 767, 'Dept': 'Marketing'}
在 python 中檢查物件
示例
# Inspect an object in Python myList =[1, 3, 4, 7, 9] print(dir(myList))
輸出
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP