分享25個實用的一行Python代碼,你都用過嗎?
入門教程、案例源碼、學(xué)習(xí)資料、讀者群
請訪問: python666.cn
在學(xué)習(xí)Python的過程當(dāng)中,有很多復(fù)雜的任務(wù)其實只需要一行代碼就可以解決,那么今天就來給大家介紹25個實用的一行Python代碼,希望對大家能夠有所幫助。
1.兩個字典的合并
x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
將兩個字典合并起來,代碼如下
x.update(y)
print(x)
output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
2.兩個列表的合并
x = ['a', 'b']
y = ['c', 'd', 'e']
將上面兩個列表合并起來,代碼如下
x.extend(y)
print(x)
output
['a', 'b', 'c', 'd', 'e']
x += y
print(x)
output
['a', 'b', 'c', 'd', 'e']
3.計算列表中元素出現(xiàn)的頻率
python當(dāng)中的collections模塊來實現(xiàn),例如
from collections import Counter
my_list = ['a', 'b', 'b', 'a', 'a', 'a', 'c', 'c', 'b', 'd']
print(Counter(my_list).most_common())
output
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]
篩選第一個元素的操作即可
print(Counter(my_list).most_common()[0])
output
('a', 4)
a,總共出現(xiàn)了4次
當(dāng)然要是在后面再添加一個[0],意思就是篩選出出現(xiàn)頻率最多的元素
print(Counter(my_list).most_common()[0][0])
output
a
4.計算獲得除法中的商和余數(shù)
//和/,而divmod方法則可以讓我們同時獲得除法運(yùn)算當(dāng)中的商和余數(shù),代碼如下
quotient, remainder = divmod(37, 5)
print(quotient, remainder)
output
7 2
5.計算得到列表當(dāng)中長度最長的字符串
words = ['Python', 'is', 'awesome']
print(max(words, key=len))
output
awesome
6.將列表中的順序倒轉(zhuǎn)
words = ['Python', 'is', 'awesome']
reverse_words = words[::-1]
print(reverse_words)
output
['awesome', 'is', 'Python']
7.文件的讀與寫
我們先將數(shù)據(jù)寫入到文件當(dāng)中
data = 'Python is awesome'
with open('file.txt', 'a', newline='\n') as f: f.write(data)
那我們從剛生成的文件當(dāng)中讀取剛寫入的數(shù)據(jù),代碼就是這么來寫
data = [line.strip() for line in open("file.txt")]
print(data)
output
['Python is awesome']
8.將字典當(dāng)中的鍵值對位置調(diào)換
staff = {'Data Scientist': 'Mike', 'Django Developer': 'Dylan'}
staff = {i:j for j, i in staff.items()}
print(staff)
output
{'Mike': 'Data Scientist', 'Dylan': 'Django Developer'}
9.將嵌套列表合并為一個列表
假設(shè)我們有這樣的一個列表
l = [[1, 2, 3], [4, 5], [6], [7, 8], [9]]
而我們最終希望列表能夠是
[1, 2, 3, 4, 5, 6, 7, 8, 9]
我們可以這么來做
flattened_list = [item for sublist in l for item in sublist
print(flattened_list)
output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
10.列表當(dāng)中數(shù)據(jù)類型的轉(zhuǎn)換
例如有下面的列表
['1', '2', '3']
我們要將其轉(zhuǎn)換成整數(shù)類型,代碼如下
print(list(map(int, ['1', '2', '3'])))
output
[1, 2, 3]
print(list(map(float, ['1', 2, '3.0', 4.0, '5', 6])))
output
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
11.將列表轉(zhuǎn)化成字典
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
cars_dict = dict(enumerate(cars))
print(cars_dict)
output
{0: 'Audi', 1: 'BMW', 2: 'Ford', 3: 'Tesla', 4: 'Volvo'}
12.將列表當(dāng)中的重復(fù)元素去除
list(set(['a', 'a', 'b', 'a', 'c']))
output
['a', 'b', 'c']
13.從列表中篩選出特定元素
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
car_1 = [car for car in cars if car[0] == "A"]
print(car_1)
output
['Audi']
Python當(dāng)中的filter方法來實現(xiàn),代碼如下
car_1 = list(filter(lambda c: c[0] == 'A', cars))
得到的結(jié)果也和上述的一樣
14.列表中的元素排序
numbers = [55, -30, 28, -36, 48, 20]
numbers.sort()
print(numbers)
output
[-36, -30, 20, 28, 48, 55]
numbers.sort(reverse=True)
numbers
output
[55, 48, 28, 20, -30, -36]
cars = ['Ford', 'Tesla', 'BMW', 'Volvo', 'Audi']
cars.sort()
print(cars)
output
['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
15.合并集合
set1 = {"1", "2", "5"}
set2 = {"4", "6", "7"}
set1.update(set2)
print(set1)
output
{'7', '6', '5', '2', '1', '4'}
16. 根據(jù)鍵來對字典進(jìn)行排序
d = {'one': 1, 'three': 4, 'five': 8, 'six': 10}
result = {key: d[key] for key in sorted(d.keys())}
print(result)
output
{'five': 8, 'one': 1, 'six': 10, 'three': 4}
17. 根據(jù)鍵值來對字典進(jìn)行排序
d = {'one': 15, 'three': 12, 'five': 8, 'six': 30}
result = {key: value for key, value in sorted(d.items(), key=lambda item: item[1])}
print(result)
output
{'five': 8, 'three': 12, 'one': 15, 'six': 30}
18. 替換字符串
"Python is a programming language. Python is awesome".replace("Python",'Java')
output
Java is a programming language. Java is awesome
19. 計算指定字符串出現(xiàn)的次數(shù)
a = 'python is a programming language. python is python.'
result = a.count('python')
print(result)
output
3
20. 將自定義方法作用在列表中的每個元素
from functools import reduce
reduce(lambda x, y: x*y, [2, 2, 3, 4])
output
48
21. 找到最大的那個數(shù)
find_max = lambda x,y: x if x > y else y
result = find_max(5,20)
output
20
22. 將矩陣轉(zhuǎn)置
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
transposed = [list(i) for i in zip(*a)]
print(transposed)
output
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
23. 生成斐波納契數(shù)列
1, 1, 2, 3, 5, 8,13,要生成它的代碼如下
fibo = [0, 1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(10)]
print(fibo)
output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
24. 刪除列表中的多個元素
mylist = [100, 200, 300, 400, 500]
del mylist[:3]
print(mylist)
output
[400, 500]
25. 多個if-else組合
目標(biāo)是將下面多個if-else的組合,寫在一行上面
x = 200
if x < 20:
print("小于20")
elif x == 200:
print("等于200")
else:
print("大于20且不等于200")
我們也可以將多個if-else組合放在一行上面寫
x = 200
print("小于20") if x < 20 else print("等于200") if x == 200 else print("大于20且不等于200")
作者:欣一

本書從 Python 和 Excel 結(jié)合使用的角度講解處理分析數(shù)據(jù)的思路、方法與實戰(zhàn)應(yīng)用。不論是希望從事數(shù)據(jù)分析崗位的學(xué)習(xí)者,還是其他職業(yè)的辦公人員,都可以通過本書的學(xué)習(xí)掌握 Python 分析數(shù)據(jù)的技能。書中創(chuàng)新性地將 ChatGPT 引入到教學(xué)當(dāng)中,用 ChatGPT 答疑并提供實訓(xùn)代碼,并介紹了使用 ChatGPT 輔助學(xué)習(xí)的一些實用技巧,給學(xué)習(xí)者帶來全新的學(xué)習(xí)方式。
讀者朋友們購買后可在后臺聯(lián)系我,加入讀者交流群,Crossin會為你開啟陪讀模式,解答你在閱讀本書時的一切疑問。
_往期文章推薦_
【教程】: python
