python初學者
Python is among the most widely used market programming languages in the world. This is because of a variety of driving factors:
Python是世界上使用最廣泛的市場編程語言之一。 這是由于多種驅動因素:
- It’s simple to understand. 很容易理解。
- It’s incredibly versatile. 它的用途非常廣泛。
- It contains a broad collection of modules and libraries. 它包含大量的模塊和庫。
The brevity and higher readability make it quite prominent among all developers.
簡潔和更高的可讀性使它在所有開發人員中都非常突出。
As a vital part of my job as a data scientist, I use Python every day. Along the way, I’ve gained a few amazing hacks. I’ve listed some of those below.
作為數據科學家工作的重要組成部分,我每天都使用Python。 一路上,我獲得了一些驚人的技巧。 我在下面列出了其中一些。
20個必要的Python技巧 (20 Necessary Python Hacks)
1.交換值 (1. Swapping values)
Number swaps normally involve values storage in temporary variables. Yet we could do it by using a single line of code through this Python tip, with no transient variables.
數字交換通常涉及將值存儲在臨時變量中。 然而,我們可以通過使用此Python技巧中的單行代碼來完成此操作,而無需使用瞬態變量。
2.列表中所有項目的一串 (2. One string of all items within a list)
When you have to convolve a string list, you could do this one after another through updating each item with the help of a for
loop. It will, nevertheless, be cumbersome, particularly if the list has been lengthy. Within Python, strings are immutable. Thus, in each duo of concatenation, the left and right strings should be copied into a fresh string.
當您需要卷積字符串列表時,可以在for
循環的幫助下通過更新每個項目來一個接一個地執行此操作。 但是,這將很麻煩,特別是如果清單很長的話。 在Python中,字符串是不可變的。 因此,在每個串聯中,左字符串和右字符串應復制到新字符串中。
Using a join()
function, as seen here, is a cleaner solution:
如此處所示,使用join()
函數是一種更干凈的解決方案:
p = ["Python", "is", "a", "popular", "language"]
print(" ".join(p))output
Python is a popular language
3.列表中最常見的元素 (3. Most common element in the list)
Identify the most frequently occurring value in a list. If various items occur equally print one of them.
標識列表中最頻繁出現的值。 如果各種項目均等出現,請打印其中一項。
Create a list set to remove the redundant values. So the maximum number of events of each item is found in the set, and then we consider the maximum.
創建一個列表集以刪除冗余值。 因此,可以在集合中找到每個項目的最大事件數,然后考慮最大值。
list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4]
print(max(set(list1), key = list1.count))output
3
4.測試兩個字符串是否是字謎 (4. Test if two strings are anagrams)
Solve the problems above to figure out whether two strings are anagrams. Given two strings string_1
and string_2
, test if both the strings are anagrams of each other.
解決上述問題,找出兩個字符串是否為字謎。 給定兩個字符串string_1
和string_2
,測試兩個字符串是否彼此相同。
5.反轉字符串 (5. Reverse a string)
Slicing is a handy tip in Python which can also be used to reverse the sequence of items within a string.
切片是Python中的一個方便技巧,它也可以用于反轉字符串中的項目順序。
6.反向列出 (6. Reverse a list)
A copy of the list is created from this approach, and as well, the list is not sorted in order. To create a copy, you need more room to hold all the existing elements.
列表的副本是通過這種方法創建的,并且列表也沒有按順序排序。 要創建副本,您需要更多空間來容納所有現有元素。
7.轉置矩陣 (7. Transpose a matrix)
Transposing a matrix means transforming columns to rows and vice versa. With Python, you can unzip a list that is a transpose of the matrix by using the following code with the zip
function in combination with the *
tool.
轉置矩陣意味著將列轉換為行,反之亦然。 使用Python,您可以將以下代碼與zip
函數結合使用,并結合使用*
工具來解壓縮作為矩陣轉置的列表。
8.鏈式比較 (8. Chained comparison)
In programming, it is quite normal to test more than two conditions. Let’s assume that we need to test the following:
在編程中,測試兩個以上的條件是很正常的。 假設我們需要測試以下內容:
p < q< r
There is indeed a smarter process of writing it with comparison chaining in Python. The operator chaining has been represented as below:
實際上,使用Python中的比較鏈來編寫它確實有一個更聰明的過程。 操作員鏈表示如下:
if p< q< r:
{.....}
Comparisons return boolean values True
or False
.
比較返回布爾值True
或False
。
See the example below:
請參閱以下示例:
9.字典'get' (9. Dictionary ‘get’)
Below is a traditional way of accessing a value for a key in Python dictionaries.
以下是在Python詞典中訪問鍵值的傳統方法。
dict = {"P":1, "Q":2}
print(dict["P"])
print(dict["R"])
The concern is that the third line of the code yields a key error:
值得關注的是,代碼的第三行產生了一個關鍵錯誤:
Traceback (most recent call last):
File ".\dict.py", line 3, in
print (dict["R"])
KeyError: 'R'
To prevent these cases, the get()
function is used. This technique provides the value for a specific key when available in the dictionary. when it isn’t, None
will be returned (if only one argument is used with get())
.
為避免這些情況,使用了get()
函數。 當在字典中可用時,此技術可提供特定鍵的值。 否則,將不返回None
(如果只有一個參數與get())
。
10.按值對字典排序 (10. Sort dictionary by value)
Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications, ranging from the competitive domain to the developer domain.
排序一直是日常編程中的有用工具。 Python詞典廣泛用于從競爭領域到開發人員領域的許多應用程序中。
Construct a dictionary, as well as show all keys in alphabetical order. List both the alphabetically sorted keys and values by the value.
構造一個字典,并按字母順序顯示所有鍵。 列出按字母順序排序的鍵和按值列出的值。
11.清單理解 (11. List comprehension)
To construct fresh lists from different iterables, list comprehensions are used. Since list comprehensions yield lists, they contain parentheses that include the expression which gets executed to every element. List comprehension is simpler, as the Python interpreter is designed to detect a recurring pattern in looping.
為了從不同的可迭代對象構造新的列表,使用列表推導。 由于列表推導產生列表,因此它們包含的括號包括對每個元素執行的表達式。 列表理解更簡單,因為Python解釋器旨在檢測循環中的重復模式。
12.實施計劃的一部分所花費的時間 (12. Time consumed to implement a part of the program)
This one focuses on showing how to compute the time taken by the program or a section of a program to execute. Calculating time helps to optimize your Python script to perform better.
本節重點介紹如何計算程序或程序的一部分執行所花費的時間。 計算時間有助于優化Python腳本以使其表現更好。
13.合并字典 (13. Merge dictionaries)
This is a trick in Python where a single expression is used to merge two dictionaries and store the result in a third dictionary. The single expression is **
. This does not affect the other two dictionaries. **
implies that the argument is a dictionary. Using **
is a shortcut that allows you to pass multiple arguments to a function directly by using a dictionary.
這是Python中的一個技巧,其中單個表達式用于合并兩個字典并將結果存儲在第三個字典中。 單個表達式是**
。 這不會影響其他兩個詞典。 **
表示該參數是字典。 使用**
是一種快捷方式,它允許您通過使用字典將多個參數直接傳遞給函數。
Using this, we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.
使用此方法,我們首先將第一個字典的所有元素傳遞給第三個字典,然后將第二個字典傳遞給第三個字典。 這將替換第一個字典的重復鍵。
14.數字化 (14. Digitize)
Here is the code that uses map()
, list comprehension, and a simpler approach for digitizing.
這是使用map()
,列表理解和一種更簡單的數字化方法的代碼。
15.測試唯一性 (15. Test for uniqueness)
Some list operations require us to test when total items in the list are distinct. This usually happens when we try to perform the set operations in a list. Hence, this particular utility is essential at these times.
一些列表操作要求我們測試列表中的總項目何時不同。 當我們嘗試在列表中執行設置操作時,通常會發生這種情況。 因此,此特定實用程序在這些時候至關重要。
16.使用枚舉 (16. Using enumeration)
Using enumerators, finding an index is quick when you’re within a loop.
使用枚舉器,當您處于循環中時,可以快速找到索引。
17.在一行中評估任意數字的階乘 (17. Evaluate the factorial of any number in a single line)
This one gives you a method to find the factorial of a given number in one line.
這為您提供了一種在一行中查找給定數字的階乘的方法。
18.返回幾個函數的元素 (18. Return several functions’ elements)
This function is not offered by numerous computer languages. For Python, though, functions yield several elements.
許多計算機語言均未提供此功能。 但是,對于Python,函數產生幾個元素。
Kindly review the following instance to understand how it performs.
請查看以下實例以了解其性能。
19.合并一個真實的Python switch-case語句 (19. Incorporate a true Python switch-case statement)
Below is the script used to replicate a switch-case structure with a dictionary.
下面是用于復制帶有字典的切換案例結構的腳本。
20.使用splat運算符解包函數參數 (20. With splat operator unpacking function arguments)
The splat operator provides an efficient way of unpacking lists of arguments. For clarification, please go through the following illustration:
splat運算符提供了一種解壓縮參數列表的有效方法。 為了澄清起見,請檢查下圖:
尾注 (The Ending Note)
I hope the aforementioned 20 necessary Python hacks will allow you to accomplish your Python jobs swiftly and effectively. You can further consider those or your assignments and programs.
我希望前面提到的20個必要的Python技巧可以使您快速有效地完成Python工作。 您可以進一步考慮這些或您的作業和程序。
Some I found while browsing the Python Standard Library docs. A few others I found searching through PyTricks.
我在瀏覽Python標準庫文檔時發現的一些。 我發現其他一些人通過PyTricks進行搜索。
If you think I should include more or have suggestions, please do comment below.
如果您認為我應該包括更多內容或有建議,請在下面做評論。
Thanks for reading!
謝謝閱讀!
翻譯自: https://medium.com/better-programming/20-valuable-and-essential-python-hacks-for-beginners-112954560aff
python初學者
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/387880.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/387880.shtml 英文地址,請注明出處:http://en.pswp.cn/news/387880.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!