網站首頁 編程語言 正文
1.引言
在這篇文章中,我們將討論最常用的python技巧。大多數這些技巧都是我在日常工作中使用過的簡單的Trick,我覺得好東西就是要拿出來和大家一起分享。
2.技巧總結
2.1.處理用戶的多個輸入
有時我們需要從用戶那里獲得多個輸入,以便使用循環或任何迭代,一般的寫法如下:
# bad practice碼 n1 = input("enter a number : ") n2 = input("enter a number : ") n2 = input("enter a number : ") print(n1, n2, n3)
但是更好的處理方法如下:
# good practice n1, n2, n3 = input("enter a number : ").split() print(n1, n2, n3)
2.2.處理多個條件語句
如果我們在代碼中需要檢查多個條件語句,此時我們可以使用 all() 或 any() 函數來實現我們的目標。一般來說, 當我們有多個 and 條件時使用 all(),當我們有多個 or 條件時使用 any()。這種用法將使我們的代碼更加清晰易讀,可以方便我們在調試時不會遇到麻煩。
對于all()的一般例子如下:
size = "lg" color = "blue" price = 50 # bad practice if size == "lg" and color == "blue" and price < 100: ? ? print("Yes, I want to but the product.")
更好的處理方法如下:
# good practice conditions = [ ? ? size == "lg", ? ? color == "blue", ? ? price < 100, ] if all(conditions): ? ? print("Yes, I want to but the product.")
對于any()的一般例子如下:
# bad practice size = "lg" color = "blue" price = 50 if size == "lg" or color == "blue" or price < 100: ? ? print("Yes, I want to but the product.")
更好的處理方法如下:
# good practice conditions = [ ? ? size == "lg", ? ? color == "blue", ? ? price < 100, ] if any(conditions): ? ? print("Yes, I want to but the product.")
2.3.判斷數字奇偶性
這很容易實現,我們從用戶那里得到輸入,將其轉換為整數,檢查 對數字2的求余操作,如果余數為零,則它是偶數。
print('odd' if int(input('Enter a number: '))%2 else 'even')
2.4.交換變量
在Python
中如果需要交換變量的值,我們無需定義臨時變量來操作。
我們一般使用如下代碼來實現變量交換:
v1 = 100 v2 = 200 # bad practice temp = v1 v1 = v2 v2 = temp
但是更好的處理方法如下:
v1 = 100 v2 = 200 # good practice v1, v2 = v2, v1
2.5.反轉字符串
將字符串進行反轉最簡單的實現方式為[::-1] ,代碼如下:
print("John Deo"[::-1])
2.6.判斷字符串是否為回文串
在Python中判斷一個字符串是否為回文串,只需要使用語句 string.find(string[::-1])== 0
,示
例代碼如下:
v1 = "madam" # is a palindrome string v2 = "master" # is not a palindrome string print(v1.find(v1[::-1]) == 0) # True print(v1.find(v2[::-1]) == 0) # False
2.7.盡量使用 Inline if statement
大多數情況下,我們在條件之后只有一個語句,因此使用Inline if statement 可以幫助我們編寫更簡潔的代碼。
舉例如下,一般的寫法為:
name = "ali" age = 22 # bad practices if name: ? ? print(name) if name and age > 18: ? ? print("user is verified")
但是更好的處理方法如下:
# a better approach print(name if name else "") """ here you have to define the else condition too""" # good practice? name and print(name) age > 18 and name and print("user is verified")
2.8.刪除list中的重復元素
我們不需要遍歷整個list列表來檢查重復元素,我們可以簡單地使用 set() 來刪除重復元素,
代碼如下:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] print(lst) unique_lst = list(set(lst)) print(unique_lst)
2.9.找到list中重復最多的元素
在Python中可以使用 max( )
函數并傳遞list.count
作為key,即可找出列表list中重復次數最多的元素,代碼如下:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] most_repeated_item = max(lst, key=lst.count) print(most_repeated_item)
2.10.list 生成式
Python中我最喜歡的功能就是list comprehensions
, 這個特性可以使我們編寫非常簡潔功能強大的代碼,而且這些代碼讀起來幾乎像自然語言一樣通俗易懂。
舉例如下:
numbers = [1,2,3,4,5,6,7] evens = [x for x in numbers if x % 2 is 0] odds = [y for y in numbers if y not in evens] cities = ['London', 'Dublin', 'Oslo'] def visit(city): ? ? print("Welcome to "+city) for city in cities: ? ? visit(city)
2.11.使用*args傳遞多個參數
在Python中我們可以使用*args來向函數傳遞多個參數,舉例如下:
def sum_of_squares(n1, n2) ? ? return n1**2 + n2**2 print(sum_of_squares(2,3)) # output: 13 """ what ever if you want to pass, multiple args to the function? as n number of args. so let's make it dynamic. """? def sum_of_squares(*args): ? ? return sum([item**2 for item in args]) # now you can pass as many parameters as you want print(sum_of_squares(2, 3, 4)) print(sum_of_squares(2, 3, 4, 5, 6))
2.12.在循環時處理下標
有時我們在工作中,想要獲得循環中元素的下標,一般來說,比較優雅的寫法如下:
lst = ["blue", "lightblue", "pink", "orange", "red"] for idx, item in enumerate(lst): ? ? ?print(idx, item)
2.13.拼接list中多個元素
在Python中一般使用Join()
函數來將list中所有元素拼接到一起,當然我們也可以在拼接的時候添加拼接符號
樣例如下:
names = ["john", "sara", "jim", "rock"] print(", ".join(names))
2.14.將兩個字典進行合并
在Python中我們可以使用{**dict_name, **dict_name2, … }
將多個字典進行合并,
樣例如下:
d1 = {"v1": 22, "v2": 33} d2 = {"v2": 44, "v3": 55} d3 = {**d1, **d2} print(d3)
結果如下:
{'v1': 22, 'v2': 44, 'v3': 55}
2.15.使用兩個list生成一個字典
在Python中,如果我們需要將兩個列表中對應的元素組成字典,那么我們可以使用 zip 功能來方便地做到這一點。
代碼如下:
keys = ['a', 'b', 'c'] vals = [1, 2, 3] zipped = dict(zip(keys, vals))
2.16.字典按照value進行排序
在Python中我們使用sorted()
函數來按照字典的value來對其進行排序.
代碼如下:
d = { ? ? "v1": 80, ? ? "v2": 20, ? ? "v3": 40, ? ? "v4": 20, ? ? "v5": 10, } sorted_d = dict(sorted(d.items(), key=lambda item: item[1])) print(sorted_d)
當然我們也可以使用itemgetter( ) 來替代上述 lambda函數,
代碼如下:
from operator import itemgetter sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
更進一步,我們也可以通過傳遞reverse=True
對其進行降序排序:
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
2.17.Pretty print
在Python
中使用Print()
函數,有時候的輸出賊拉拉丑陋,此時我們使用pprint
可以使輸出更加美觀,
樣例如下:
from pprint import pprint data = { ? ? "name": "john deo", ? ? "age": "22", ? ? "address": {"contry": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"}, ? ? "attr": {"verified": True, "emialaddress": True}, } print(data) pprint(data)
輸出如下:
{'name': 'john deo', 'age': '22', 'address': {'contry': 'canada', 'state': 'an state of canada :)', 'address': 'street st.34 north 12'}, 'attr': {'verified': True, 'emialaddress': True}} {'address': {'address': 'street st.34 north 12', ? ? ? ? ? ? ?'contry': 'canada', ? ? ? ? ? ? ?'state': 'an state of canada :)'}, ?'age': '22', ?'attr': {'emialaddress': True, 'verified': True}, ?'name': 'john deo'}
使用pprint函數可以讓字典的輸出更加容易閱讀.
原文鏈接:https://blog.csdn.net/sgzqc/article/details/122548784
相關推薦
- 2022-04-28 C++實現簡單班級成績管理系統_C 語言
- 2022-10-09 C#實現插入排序_C#教程
- 2022-07-30 Git操作相關問題(pull/push/clone/)
- 2023-12-02 vscode無法連接寶塔ftp排雷
- 2022-06-29 C語言詳細講解常用字符串處理函數_C 語言
- 2022-07-25 SQL?Server系統函數介紹_MsSql
- 2022-11-17 Python操作MongoDB的教程詳解(插,查,改,排,刪)_python
- 2022-07-13 4:thingsboard的實體與關系
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支