許多程序員喜歡Python/ target=_blank class=infotextkey>Python,因為它的語法簡單簡潔。下面提供的這些 Python 代碼足夠簡練,可用于解決常見問題。
1.提取字典的鍵值對
dict1 = {'A':33, 'B':43, 'C':88, 'D':56}
# 提取字典中值大于50的鍵值對
dict2 = { key:value for key, value in dict1.items() if value > 50 }
print(dict2)
set1 = {'A','C'}
# 提取字典中鍵包含在集合中的鍵值對
dict3 = { key:value for key,value in dict1.items() if key in set1 }
print(dict3)
「輸出:」
{'C': 88, 'D': 56} {'A': 33, 'C': 88}
2.搜索和替換文本
可以使用 str.replace() 方法搜索和替換字符串中的文本。
str1 = "http://www.zbxx.NET"
str1 = str1.replace("http", "https")
print(str1)
「輸出:」
https://www.zbxx.net
對于更復雜的搜索替換,可以使用 re 模塊。Python 中的正則表達式可以使復雜的任務變得更加容易。
3.過濾列表元素
可以使用列表推導式根據特定條件過濾列表中的元素。
list1 = [12, 56, 34, 76, 79]
# 提取列表中大于50的元素
list2 = [i for i in list1 if i>50]
print(list2)
「輸出:」
[56, 76, 79]
4.對齊字符串
可以使用 ljust()、rjust() 和 center() 方法對齊字符串。 可以實現左對齊、右對齊及使字符串在給定寬度的范圍居中對齊。
str1 = "Python"
print(str1.ljust(10))
print(str1.center(10))
print(str1.rjust(10))
「輸出:」
Python
Python
Python
還可以使用字符填充。
str1 = "Python"
print(str1.ljust(10, '#'))
print(str1.center(10, '#'))
print(str1.rjust(10, '#'))
「輸出:」
Python####
##Python##
####Python
5.將序列拆解為單獨的變量
可以使用賦值運算符將任何序列拆解到變量中,只要變量的數量和序列的元素數量相互匹配。
tup1 = (1, 2, 3)
a, b, c = tup1
print(a,b,c)
「輸出:」
1 2 3
6.任意數量參數的函數
自定義函數中,需要使用 “*” 來接受任意數量的參數。
def mysum(value1,*value):
s=value1+sum(value)
print(s)
mysum(10, 10)
mysum(10, 10, 10)
「輸出:」
20 30
7. 反向迭代
可以使用 reversed() 函數、range() 函數和切片技術以相反的順序迭代序列。
list1 = [1, 2, 3, 4, 5, 6]
for i in reversed(list1):
print(i,end='')
list1 = [1, 2, 3, 4, 5, 6]
for i in range(len(list1) -1, -1, -1):
print(list1[i],end='')
list1 = [1, 2, 3, 4, 5, 6]
for i in list1[::-1]:
print(i,end='')
「輸出:」
654321
8.寫入尚不存在的文件
如果只想在文件不存在時才寫入該文件,則需要在 x 模式(獨占創建模式)下打開該文件。
with open('abc.txt', 'x') as f:
f.write('Python')
如果文件已經存在,則此代碼將導致 Python 出錯:FileExistsError。






