日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

好用到哭!你需要立刻学会的20个Python代码段,你get到了吗?

發布時間:2025/3/15 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 好用到哭!你需要立刻学会的20个Python代码段,你get到了吗? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

?

Python是一種非BS編程語言。設計簡單和易讀性是它廣受歡迎的兩大原因。正如Python的宗旨:美麗勝于丑陋,顯式勝于隱式。

記住一些幫助提高編碼設計的常用小訣竅是有用的。在必要時刻,這些小訣竅能夠減少你上網查Stack Overflow的麻煩。而且它們會在每日編程練習中助你一臂之力。

1. 反轉字符串

以下代碼使用Python切片操作來反轉字符串。

# Reversing a string using slicing

my_string = "ABCDE"

reversed_string = my_string[::-1]

print(reversed_string)

# Output

# EDCBA

2. 使用標題類(首字母大寫)

以下代碼可用于將字符串轉換為標題類。這是通過使用字符串類中的title()方法來完成。

my_string = "my name is chaitanya baweja"

# using the title() function of string class

new_string = my_string.title()

print(new_string)

# My Name Is Chaitanya Baweja

3. 查找字符串的唯一要素

以下代碼可用于查找字符串中所有的唯一要素。我們使用其屬性,其中一套字符串中的所有要素都是唯一的。

my_string = "aavvccccddddeee"

# converting the string to a set

temp_set = set(my_string)

# stitching set into a string using join

new_string = ''.join(temp_set)

4. 輸出 n次字符串或列表

你可以對字符串或列表使用乘法(*)。如此一來,可以按照需求將它們任意倍增。

n = 3 # number of repetitions

my_string = "abcd"

my_list = [1,2,3]

print(my_string*n)

# abcdabcdabcd

print(my_list*n)

# [1,2,3,1,2,3,1,2,3]

import streamlit as st

一個有趣的用例是定義一個具有恒定值的列表,假設為零。

5. 列表解析

在其他列表的基礎上,列表解析為創建列表提供一種優雅的方式。

以下代碼通過將舊列表的每個對象乘兩次,創建一個新的列表。

# Multiplying each element in a list by 2

original_list = [1,2,3,4]

new_list = [2*x for x in original_list]

print(new_list)

# [2,4,6,8]

6. 兩個變量之間的交換值

?

Python可以十分簡單地交換兩個變量間的值,無需使用第三個變量。

a = 1

b = 2

a, b = b, a

print(a) # 2

print(b) # 1

7. 將字符串拆分成子字符串列表

通過使用.split()方法,可以將字符串分成子字符串列表。還可以將想拆分的分隔符作為參數傳遞。

string_1 = "My name is Chaitanya Baweja"

string_2 = "sample/ string 2"

# default separator ' '

print(string_1.split())

# ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# defining separator as '/'

print(string_2.split('/'))

# ['sample', ' string 2']

8. 將字符串列表整合成單個字符串

join()方法將字符串列表整合成單個字符串。在下面的例子中,使用comma分隔符將它們分開。

list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# Using join with the comma separator

print(','.join(list_of_strings))

# My,name,is,Chaitanya,Baweja

9. 檢查給定字符串是否是回文(Palindrome)

反轉字符串已經在上文中討論過。因此,回文成為Python中一個簡單的程序。

my_string = "abcba"

m if my_string == my_string[::-1]:

? ? print("palindrome")

else:

? ? print("not palindrome")

# palindrome

10. 列表的要素頻率

有多種方式都可以完成這項任務,而我最喜歡用Python的Counter 類。Python計數器追蹤每個要素的頻率,Counter()反饋回一個字典,其中要素是鍵,頻率是值。

也使用most_common()功能來獲得列表中的most_frequent element。

# finding frequency of each element in a list

from collections import Counter

my_list = ['a','a','b','b','b','c','d','d','d','d','d']

count = Counter(my_list) # defining a counter object

print(count) # Of all elements

# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})

print(count['b']) # of individual element

# 3

print(count.most_common(1)) # most frequent element

# [('d', 5)]

11. 查找兩個字符串是否為anagrams

Counter類的一個有趣應用是查找anagrams。

anagrams指將不同的詞或詞語的字母重新排序而構成的新詞或新詞語。

如果兩個字符串的counter對象相等,那它們就是anagrams。

From collections import Counter

str_1, str_2, str_3 = "acbde", "abced", "abcda"

cnt_1, cnt_2, cnt_3? = Counter(str_1), Counter(str_2), Counter(str_3)

if cnt_1 == cnt_2:

? ? print('1 and 2 anagram')

if cnt_1 == cnt_3:

? ? print('1 and 3 anagram')

12. 使用try-except-else塊

通過使用try/except塊,Python 中的錯誤處理得以輕松解決。在該塊添加else語句可能會有用。當try塊中無異常情況,則運行正常。

如果要運行某些程序,使用 finally,無需考慮異常情況。

a, b = 1,0

try:

? ? print(a/b)

? ? # exception raised when b is 0

except ZeroDivisionError:

? ? print("division by zero")

? ? print("no exceptions raised")

finally:

? ? print("Run this always")

13.使用列舉獲取索引和值對

以下腳本使用列舉來迭代列表中的值及其索引。

my_list = ['a', 'b', 'c', 'd', 'e']

for index, value in enumerate(my_list):

? ? print('{0}: {1}'.format(index, value))

# 0: a

# 1: b

# 2: c

# 3: d

# 4: e

14. 檢查對象的內存使用

以下腳本可用來檢查對象的內存使用。

import sys

num = 21

print(sys.getsizeof(num))

# In Python 2, 24

# In Python 3, 28

15. 合并兩個字典

在Python 2 中,使用update()方法合并兩個字典,而Python3.5 使操作過程更簡單。

在給定腳本中,兩個字典進行合并。我們使用了第二個字典中的值,以免出現交叉的情況。

dict_1 = {'apple': 9, 'banana': 6}

dict_2 = {'banana': 4, 'orange': 8}

combined_dict = {**dict_1, **dict_2}

print(combined_dict)

# {'apple': 9, 'banana': 4, 'orange': 8}

16. 執行一段代碼所需時間

下面的代碼使用time 軟件庫計算執行一段代碼所花費的時間。

import time

start_time = time.time()

# Code to check follows

a, b = 1,2

c = a+ b

# Code to check ends

end_time = time.time()

time_taken_in_micro = (end_time-?start_time)*(10**6)

print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

17. 列表清單扁平化

有時你不確定列表的嵌套深度,而且只想全部要素在單個平面列表中。

如果大家對Python感興趣的話,可以加一下我的微信哦:abb436574,免費領取一套學習資料和視頻課程喲~

可以通過以下方式獲得:

from iteration_utilities import deepflatten

# if you only have one depth nested_list, use this

def flatten(l):

? return [item for sublist in l for item in sublist]

l = [[1,2,3],[3]]

print(flatten(l))

# [1, 2, 3, 3]

# if you don't know how deep the list is nested

l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]

print(list(deepflatten(l, depth=3)))

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

若有正確格式化的數組,Numpy扁平化是更佳選擇。

18. 列表取樣

通過使用random軟件庫,以下代碼從給定的列表中生成了n個隨機樣本。

import random

num_samples = 2

samples = random.sample(my_list,num_samples)

print(samples)

# [ 'a', 'e'] this will have any 2 random values

強烈推薦使用secrets軟件庫生成用于加密的隨機樣本。

以下代碼僅限用于Python 3。

import secrets? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # imports secure module.

secure_random = secrets.SystemRandom()? ? ? # creates a secure random object.

my_list = ['a','b','c','d','e']

samples = secure_random.sample(my_list, num_samples)

# [ 'e', 'd'] this will have any 2 random values

19. 數字化

以下代碼將一個整數轉換為數字列表。

num = 123456

# using map

list_of_digits = list(map(int, str(num)))

print(list_of_digits)

# [1, 2, 3, 4, 5, 6]

# using list comprehension

list_of_digits = [int(x) for x in str(num)]

20. 檢查唯一性

以下函數將檢查一個列表中的所有要素是否唯一。

def unique(l):

? ? if len(l)==len(set(l)):

? ? ? ? print("All elements are unique")

? ??else:

? ? ? ? print("List has duplicates")

unique([1,2,3,4])

# All elements are unique

unique([1,1,2,3])

# List has duplicates

總結

以上是生活随笔為你收集整理的好用到哭!你需要立刻学会的20个Python代码段,你get到了吗?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。