日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
17條好用的Python技巧分享!

正文

創(chuàng)新互聯(lián)公司是專業(yè)的網(wǎng)站建設(shè)公司,提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)站設(shè)計(jì)等網(wǎng)站開發(fā)一體化解決方案;包括H5網(wǎng)站設(shè)計(jì),微信小程序,網(wǎng)站定制,企業(yè)網(wǎng)站建設(shè),電子商務(wù)商城網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),建網(wǎng)站,PHP網(wǎng)站建設(shè),軟件開發(fā),軟文推廣,網(wǎng)站營銷。歡迎做網(wǎng)站的企業(yè)前來合作洽談,創(chuàng)新互聯(lián)公司將竭誠為您服務(wù)!

大家好,我是Python人工智能技術(shù)。

在這篇文章中,我們將討論最常用的python技巧。大多數(shù)這些技巧都是我在日常工作中使用過的簡單的Trick,我覺得好東西就是要拿出來和大家一起分享。

閑話少說,我們直接開始吧!:)

技巧總結(jié)

1、處理用戶的多個(gè)輸入

有時(shí)我們需要從用戶那里獲得多個(gè)輸入,以便使用循環(huán)或任何迭代,一般的寫法如下:

# 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、處理多個(gè)條件語句

如果我們在代碼中需要檢查多個(gè)條件語句,此時(shí)我們可以使用 all() 或any() 函數(shù)來實(shí)現(xiàn)我們的目標(biāo)。一般來說, 當(dāng)我們有多個(gè) and 條件時(shí)使用 all(),當(dāng)我們有多個(gè) or 條件時(shí)使用 any()。這種用法將使我們的代碼更加清晰易讀,可以方便我們在調(diào)試時(shí)不會(huì)遇到麻煩。

對于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.")

3、 判斷數(shù)字奇偶性

這很容易實(shí)現(xiàn),我們從用戶那里得到輸入,將其轉(zhuǎn)換為整數(shù),檢查 對數(shù)字2的求余操作,如果余數(shù)為零,則它是偶數(shù)。

print('odd' if int(input('Enter a number: '))%2 else 'even')

4、 交換變量

在Python中如果需要交換變量的值,我們無需定義臨時(shí)變量來操作。我們一般使用如下代碼來實(shí)現(xiàn)變量交換:

v1 = 100
v2 = 200
# bad practice
temp = v1
v1 = v2
v2 = temp

但是更好的處理方法如下:

v1 = 100
v2 = 200
# good practice
v1, v2 = v2, v1

5、 判斷字符串是否為回文串

將字符串進(jìn)行反轉(zhuǎn)最簡單的實(shí)現(xiàn)方式為 [::-1] ,代碼如下:

print("John Deo"[::-1])

6、 反轉(zhuǎn)字符串

在Python中判斷一個(gè)字符串是否為回文串,只需要使用語句

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

7、 盡量使用 Inline if statement

大多數(shù)情況下,我們在條件之后只有一個(gè)語句,因此使用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")

8、 刪除list中的重復(fù)元素

我們不需要遍歷整個(gè)list列表來檢查重復(fù)元素,我們可以簡單地使用 set() 來刪除重復(fù)元素,代碼如下:

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)

9、 找到list中重復(fù)最多的元素

在Python中可以使用 max( ) 函數(shù)并傳遞 list.count 作為key,即可找出列表list中重復(fù)次數(shù)最多的元素,代碼如下:

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)

10、 list 生成式

Python中我最喜歡的功能就是list comprehensions , 這個(gè)特性可以使我們編寫非常簡潔功能強(qiáng)大的代碼,而且這些代碼讀起來幾乎像自然語言一樣通俗易懂。舉例如下:

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)

11、 使用*args傳遞多個(gè)參數(shù)

在Python中我們可以使用*args來向函數(shù)傳遞多個(gè)參數(shù),舉例如下:

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))

12、 在循環(huán)時(shí)處理下標(biāo)

有時(shí)我們在工作中,想要獲得循環(huán)中元素的下標(biāo),一般來說,比較優(yōu)雅的寫法如下:

lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)

13、 拼接list中多個(gè)元素

在Python中一般使用Join() 函數(shù)來將list中所有元素拼接到一起,當(dāng)然我們也可以在拼接的時(shí)候添加拼接符號(hào),樣例如下:

names = ["john", "sara", "jim", "rock"]
print(", ".join(names))

14、 將兩個(gè)字典進(jìn)行合并

另外,搜索公眾號(hào)頂級(jí)Python后臺(tái)回復(fù)“進(jìn)階”,獲取一份驚喜禮包。

在Python中我們可以使用{**dict_name, **dict_name2, … }將多個(gè)字典進(jìn)行合并,樣例如下:

d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)

結(jié)果如下:

{'v1': 22, 'v2': 44, 'v3': 55}

15 使用兩個(gè)list生成一個(gè)字典

在Python中,、果我們需要將兩個(gè)列表中對應(yīng)的元素組成字典,那么我們可以使用 zip 功能來方便地做到這一點(diǎn)。代碼如下:

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
16、 字典按照value進(jìn)行排序

在Python中我們使用sorted()函數(shù)來按照字典的value來對其進(jìn)行排序.代碼如下:

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)
當(dāng)然我們也可以使用itemgetter( )來替代上述 lambda函數(shù),代碼如下:
from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1)))

更進(jìn)一步,我們也可以通過傳遞 reverse=True 對其進(jìn)行降序排序:

sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))

17、 Pretty print

在Python中使用Print()函數(shù),有時(shí)候的輸出賊拉拉丑陋,此時(shí)我們使用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函數(shù)可以讓字典的輸出更加容易閱讀。


分享名稱:17條好用的Python技巧分享!
網(wǎng)頁鏈接:http://m.5511xx.com/article/djhcpps.html