python初學者_面向初學者的20種重要的Python技巧

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_1string_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.

比較返回布爾值TrueFalse

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,一經查實,立即刪除!

相關文章

主串與模式串的匹配

主串與模式串的匹配 &#xff08;1&#xff09;BF算法&#xff1a; BF算法比較簡單直觀&#xff0c;其匹配原理是主串S.ch[i]和模式串T.ch[j]比較&#xff0c;若相等&#xff0c;則i和j分別指示串中的下一個位置&#xff0c;繼續比較后續字符&#xff0c;若不相等&#xff0c;從…

什么是 DDoS 攻擊?

歡迎訪問網易云社區&#xff0c;了解更多網易技術產品運營經驗。 全稱Distributed Denial of Service&#xff0c;中文意思為“分布式拒絕服務”&#xff0c;就是利用大量合法的分布式服務器對目標發送請求&#xff0c;從而導致正常合法用戶無法獲得服務。通俗點講就是利用網絡…

nginx 并發過十萬

一般來說nginx 配置文件中對優化比較有作用的為以下幾項&#xff1a; worker_processes 8; nginx 進程數&#xff0c;建議按照cpu 數目來指定&#xff0c;一般為它的倍數。 worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000; 為每…

貝葉斯網絡建模

I am feeling sick. Fever. Cough. Stuffy nose. And it’s wintertime. Do I have the flu? Likely. Plus I have muscle pain. More likely.我感到惡心。 發熱。 咳嗽。 鼻塞。 現在是冬天。 我有流感嗎&#xff1f; 可能吧 另外我有肌肉疼痛。 更傾向于。 Bayesian networ…

長春南關區凈月大街附近都有哪些課后班?

長春南關區凈月大街附近都有哪些課后班&#xff1f;在學校的教育不能滿足廣大學生的需求的時候&#xff0c;一對一輔導、文化課輔導、高考輔導等越來越多的家長和孩子的選擇。相對于學校的大課教育&#xff0c;一對一輔導有著自身獨特的優勢&#xff0c;一對一輔導有著學校教學…

dev中文本框等獲取焦點事件

<ClientSideEvents GotFocus"GotFocus" /> editContract.SetFocus()//設置文本框等的焦點 function GotFocus(s, e) { window.top.DLG.show(700, 600, "PrePayment/ContractSelect.aspx", "選擇", null ); }…

數據科學家數據分析師_使您的分析師和數據科學家在數據處理方面保持一致

數據科學家數據分析師According to a recent survey conducted by Dimensional Research, only 50 percent of data analysts’ time is actually spent analyzing data. What’s the other half spent on? Data cleanup — that tedious and repetitive work that must be do…

神經網絡使用情景

神經網絡使用情景 人臉&#xff0f;圖像識別語音搜索文本到語音&#xff08;轉錄&#xff09;垃圾郵件篩選&#xff08;異常情況探測&#xff09;欺詐探測推薦系統&#xff08;客戶關系管理、廣告技術、避免用戶流失&#xff09;回歸分析 為何選擇Deeplearning4j&#xff1f; …

BZOJ4890 Tjoi2017城市

顯然刪掉的邊肯定是直徑上的邊。考慮枚舉刪哪一條。然后考慮怎么連。顯然新邊應該滿足其兩端點在各自樹中作為根能使樹深度最小。只要線性求出這個東西就可以了&#xff0c;這與求樹的重心的過程類似。 #include<iostream> #include<cstdio> #include<cmath>…

【國際專場】laravel多用戶平臺(SaaS, 如淘寶多用戶商城)的搭建策略

想不想用Laravel來搭建一個多用戶、或多租戶平臺&#xff1f;比如像淘寶那樣的多商戶平臺呢&#xff1f;聽上去很復雜&#xff0c;不是嗎&#xff1f;怎么能一個程序&#xff0c;給那么多的機構用戶來用呢&#xff1f;如何協調管理它們呢&#xff1f;數據庫怎么搭建呢&#xff…

GitHub常用命令及使用

GitHub使用介紹 摘要&#xff1a; 常用命令&#xff1a; git init 新建一個空的倉庫git status 查看狀態git add . 添加文件git commit -m 注釋 提交添加的文件并備注說明git remote add origin gitgithub.com:jinzhaogit/git.git 連接遠程倉庫git push -u origin master 將本地…

神經網絡的類型

KNN DNN SVM DL BP DBN RBF CNN RNN ANN 概述 本文主要介紹了當前常用的神經網絡&#xff0c;這些神經網絡主要有哪些用途&#xff0c;以及各種神經網絡的優點和局限性。 1 BP神經網絡 BP (Back Propagation)神經網絡是一種神經網絡學習算法。其由輸入層、中間層、輸出層組成的…

python db2查詢_如何將DB2查詢轉換為python腳本

python db2查詢Many companies are running common data analytics tasks using python scripts. They are asking employees to convert scripts that may currently exist in SAS or other toolsets to python. One step of this process is being able to pull in the same …

Dapper基礎知識三

在下剛畢業工作&#xff0c;之前實習有用到Dapper&#xff1f;這幾天新項目想用上Dapper&#xff0c;在下比較菜鳥&#xff0c;這塊只是個人對Dapper的一種總結。 Dapper&#xff0c;當項目在開發的時候&#xff0c;在沒有必要使用依賴注入的時候&#xff0c;如何做到對項目的快…

deeplearning4j

deeplearning4j 是基于java的深度學習庫&#xff0c;當然&#xff0c;它有許多特點&#xff0c;但暫時還沒學那么深入&#xff0c;所以就不做介紹了 需要學習dl4j&#xff0c;無從下手&#xff0c;就想著先看看官網的examples&#xff0c;于是&#xff0c;下載了examples程序&a…

PostgreSQL 11 1Kw TPCC , 1億 TPCB 7*24 強壓耐久測試

標簽 PostgreSQL , tpcc , tpcb 背景 TPCC, TPCB是工業標準的OLTP類型業務的數據庫測試&#xff0c;包含大量的讀、寫、更新、刪除操作。 7*24小時強壓耐久測試&#xff0c;主要看數據庫在長時間最大壓力下的 性能、穩定性、可靠性。 測試CASE &#xff1a; 1、1000萬 tpcc 2、…

推理編程_答案集編程的知識表示和推理

推理編程Read about the difference between declarative and imperative programming and learn from code examples (Answer Set Programming, Python and C).了解聲明式和命令式編程之間的區別&#xff0c;并從代碼示例(答案集編程&#xff0c;Python和C)中學習。 介紹 (In…

給Hadoop初學者的一些建議

我們介紹了新手學習hadoop的入門注意事項。這篇來談談hadoop核心知識學習。 hadoop核心知識學習: hadoop分為hadoop1.X和hadoop2.X&#xff0c;并且還有hadoop生態系統。這里只能慢慢介紹了。一口也吃不成胖子。 那么下面我們以hadoop2.x為例進行詳細介紹&#xff1a; Hadoop…

Guide AHOI2017 洛谷P3720

Description 農場主John最近在網上買了一輛新車&#xff0c;在購買汽車配件時&#xff0c;John不小心點了兩次“提交”按鈕。導致汽車上安裝了兩套GPS系統&#xff0c;更糟糕的是John在使用GPS導航時&#xff0c;兩套系統常常給出不同的路線。從地圖上看&#xff0c;John居住的…

穩坐視頻云行業第一,阿里云將用邊緣計算開辟新賽道

“CDN競爭的上半場已結束&#xff0c;中國視頻云市場格局已定&#xff0c;邊緣計算將成為下半場發展的新賽道。” 4月10日&#xff0c;阿里云視頻云總經理、邊緣計算負責人朱照遠在第七屆“亞太內容分發大會”暨CDN峰會表示。朱照遠認為&#xff0c;阿里云依靠齊全的產品矩陣、…