主頁 > 後端開發 > 新手學習Python需要知道的100個小技巧,加班一晚上終于整理出來了!

新手學習Python需要知道的100個小技巧,加班一晚上終于整理出來了!

2022-12-11 06:56:52 後端開發

哈嘍兄弟們,今天給大家分享一下Python初學需要知道的100個小技巧~

1、for回圈中的else條件
這是一個for-else方法,回圈遍歷串列時使用else陳述句,下面舉個例子,比如我們想檢查一個串列中是否包含奇數,那么可以通過for回圈,遍歷查找,

numbers = [2, 4, 6, 8, 1]

for number in numbers:
    if number % 2 == 1:
        print(number)
        break
else:
    print("No odd numbers")

 

如果找到了奇數,就會列印該數值,并且執行break陳述句,跳過else陳述句,沒有的話,就不會執行break陳述句,而是執行else陳述句,

2、從串列中獲取元素,定義多個變數

my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list

 

3、使用heapq模塊,獲取串列中n個最大或最小的元素

import heapq
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
print(heapq.nlargest(3, scores))  # [91, 87, 82]
print(heapq.nsmallest(5, scores))  # [15, 33, 33, 49, 51]

 

4、將串列中的所有元素作為引數傳遞給函式
我們可以使用 * 號,提取串列中所有的元素

my_list = [1, 2, 3, 4]

print(my_list)  # [1, 2, 3, 4]
print(*my_list)  # 1 2 3 4

 

如此便可以將串列中的所有元素,作為引數傳遞給函式

def sum_of_elements(*arg):
    total = 0
    for i in arg:
        total += i

    return total

result = sum_of_elements(*[1, 2, 3, 4])
print(result)  # 10
# 兄弟們學習python,有時候不知道怎么學,從哪里開始學,掌握了基本的一些語法或者做了兩個案例后,不知道下一步怎么走,不知道如何去學習更加高深的知識,
# 那么對于這些小伙伴們,我準備了大量的免費視頻,PDF電子書籍,以及源代碼!
# 直接在這個Q君羊 872937351 自取就好了 

 

5、獲取串列的所有中間元素

_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]
print(elements_in_the_middle)  # [2, 3, 4, 5, 6, 7]

 

6、使用一行代碼賦值多個變數

one, two, three, four = 1, 2, 3, 4

 

7、串列推導式
只用一行代碼,便可完成對陣列的迭代以及運算,比如,將串列中的每個數字提高一倍,

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]
print(squared_numbers) # [1, 4, 9, 16, 25]

 

推導式不僅串列能用,字典、集合、生成器也能使用,下面看一下,使用字典推導式,將字典的值提高一倍,

dictionary = {'a': 4, 'b': 5}
squared_dictionary = {key: num * num for (key, num) in dictionary.items()}
print(squared_dictionary)  # {'a': 16, 'b': 25}

 

8、通過Enum列舉同一標簽或一系列常量的集合
列舉是系結到唯一的常量值的一組符號名稱(成員),在列舉中,成員可以通過身份進行比較,列舉本身可以迭代,

from enum import Enum

class Status(Enum):
    NO_STATUS = -1
    NOT_STARTED = 0
    IN_PROGRESS = 1
    COMPLETED = 2

print(Status.IN_PROGRESS.name)  # IN_PROGRESS
print(Status.COMPLETED.value)  # 2

 

9、重復字串

name = "Banana"
print(name * 4)  # BananaBananaBananaBanana

 

10、比較3個數字的大小
如果想比較一個值和其他兩個值的大小情況,你可以使用簡單的數學運算式,

1 < x < 10

 

這個是最簡單的代數運算式,在Python中也是可以使用的,

x = 3

print(1 < x < 10)  # True
print(1 < x and x < 10)  # True

 

11、使用1行代碼合并字典

first_dictionary = {'name': 'Fan', 'location': 'Guangzhou'}
second_dictionary = {'name': 'Fan', 'surname': 'Xiao', 'location': 'Guangdong, Guangzhou'}

result = first_dictionary | second_dictionary

print(result)
# {'name': 'Fan', 'location': 'Guangdong, Guangzhou', 'surname': 'Xiao'}

 

12、查找元組中元素的索引

books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')
print(books.index('Mastery'))   # 3

 

13、將字串轉換為字串串列
假設你在函式中獲得輸出,原本應該是一個串列,但實際上卻是一個字串,

input = "[1,2,3]"

 

你可能第一時間會想到使用索引或者正則運算式,實際上,使用ast模塊的literal_eval方法就能搞定,

import ast

def string_to_list(string):
    return ast.literal_eval(string)

string = "[1, 2, 3]"
my_list = string_to_list(string)
print(my_list)  # [1, 2, 3]
string = "[[1, 2, 3],[4, 5, 6]]"
my_list = string_to_list(string)
print(my_list)  # [[1, 2, 3], [4, 5, 6]]

 

14、計算兩數差值
計算出2個數字之間的差值

def subtract(a, b):
    return a - b
print((subtract(1, 3)))  # -2
print((subtract(3, 1)))  # 2

 

上面的這個方法,需要考慮數值的先后順序,

def subtract(a, b):
    return a - b

print((subtract(a=1, b=3)))  # -2
print((subtract(b=3, a=1)))  # -2

 

使用命名引數,安排順序,這樣就不會出錯了,

15、用一個print()陳述句列印多個元素

print(1, 2, 3, "a", "z", "this is here", "here is something else")

 

16、在同一行列印多個元素

print("Hello", end="")
print("World")  # HelloWorld
print("Hello", end=" ")
print("World")  # Hello World
print('words',   'with', 'commas', 'in', 'between', sep=', ')
# words, with, commas, in, between

 

17、列印多個值,在每個值之間使用自定義分隔符

print("29", "01", "2022", sep="/")  # 29/01/2022

print("name", "domain.com", sep="@")  # [email protected]

 

18、不能在變數名的開頭使用數字

four_letters = "abcd" # this works
4_letters = "abcd" # this doesn’t work

 

這是Python的變數命名規則

19、不能在變數名的開頭使用運算子

+variable = "abcd"  # this doesn’t work

 

20、數字的第一位不能是0

number = 0110 # this doesn't work

 

這個確實挺神奇的

21、在變數名的任何地方使用下劃線

a______b = "abcd"  # this works
_a_b_c_d = "abcd"  # this also works

 

這并不意味著,你可以無限使用,為了代碼的易讀性,還是需要合理使用,

22、使用下劃線分割數值較大的數字

print(1_000_000_000)  # 1000000000
print(1_234_567)  # 1234567

 

如此,看到一大堆數字時,也能輕松閱讀,

23、反轉串列

my_list = ['a', 'b', 'c', 'd']
my_list.reverse()
print(my_list)  # ['d', 'c', 'b', 'a']

 

24、使用步進函式對字串切片

my_string = "This is just a sentence"
print(my_string[0:5])  # This
# Take three steps forward
print(my_string[0:10:3])  # Tsse

 

25、反向切片

my_string = "This is just a sentence"
print(my_string[10:0:-1])  # suj si sih

# Take two steps forward
print(my_string[10:0:-2])  # sjs i

 

26、使用開始或結束索引進行切片

my_string = "This is just a sentence"
print(my_string[4:])  # is just a sentence

print(my_string[:3])  # Thi

 

27、/和//的區別

print(3/2)  # 1.5
print(3//2)  # 1

 

28、==和is的區別
is:檢查兩個變數是否指向同一物件記憶體中,==:比較兩個物件的值

first_list = [1, 2, 3]
second_list = [1, 2, 3]
# 比較兩個值
print(first_list == second_list)  # True
# 是否指向同一記憶體
print(first_list is second_list)  
# False
third_list = first_list
print(third_list is first_list)  
# True

 

29、合并字典

dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}

merged = {**dictionary_one, **dictionary_two}

print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

30、檢查字串是否大于另一字串

first = "abc"
second = "def"

print(first < second)  # True

second = "ab"
print(first < second)  # False

 

31、檢查字串是否以特定字符開頭(不使用索引)

my_string = "abcdef"
print(my_string.startswith("b"))  # False

 

32、使用id()查找變數的唯一id

print(id(1))  # 4325776624
print(id(2))  # 4325776656
print(id("string"))  # 4327978288

 

33、整數、浮點數、字串、布林值和元組都是不可變的

當變數被賦值為整數、浮點數、字串、布林值、元組這些不可變型別后,該變數就會指向一個記憶體物件,如果重新給變數再賦值,它的記憶體物件就會發生改變,

number = 1
print(id(number))  # 4325215472
print(id(1))  # 4325215472

number = 3
print(id(number))  # 4325215536
print(id(1))  # 4325215472

 

34、字串和元組也是不可變的

此處再說明一次

name = "Fatos"
print(id(name))  # 4422282544

name = "fatos"
print(id(name))  # 4422346608

 

35、串列、集合和字典都是可變的

這意味著發生更改時,不會改變其記憶體物件,

cities = ["Beijing", "Guangzhou", "chengdu"]
print(id(cities))  # 4482699712

cities.append("Beijing")
print(id(cities))  # 4482699712

 

下面是字典

my_set = {1, 2, 3, 4}
print(id(my_set))  # 4352726176

my_set.add(5)
print(id(my_set))  # 4352726176

 

36、把一個串列變成不可變的串列

my_set = frozenset(['a', 'b', 'c', 'd'])

my_set.add("a")

 

使用frozenset()后,你就無法更改了,

37、if-elif塊可以在沒有else塊的情況下存在

但是elif不能在沒有if陳述句之前獨立存在,

def check_number(number):
    if number > 0:
        return "Positive"
    elif number == 0:
        return "Zero"

    return "Negative"

print(check_number(1))  # Positive

 

38、使用sorted()檢查2個字串是否為相同

def check_if_anagram(first_word, second_word):
    first_word = first_word.lower()
    second_word = second_word.lower()
    return sorted(first_word) == sorted(second_word)

print(check_if_anagram("testinG", "Testing"))  # True
print(check_if_anagram("Here", "Rehe"))  # True
print(check_if_anagram("Know", "Now"))  # False

 

39、獲取字符的Unicode值

print(ord("A"))  # 65
print(ord("B"))  # 66
print(ord("C"))  # 66
print(ord("a"))  # 97

 

40、獲取字典的鍵

dictionary = {"a": 1, "b": 2, "c": 3}

keys = dictionary.keys()
print(list(keys))  # ['a', 'b', 'c']

 

41、獲取字典的值

dictionary = {"a": 1, "b": 2, "c": 3}

values = dictionary.values()
print(list(values))  # [1, 2, 3]

 

42、交換字典的鍵、值位置

dictionary = {"a": 1, "b": 2, "c": 3}

reversed_dictionary = {j: i for i, j in dictionary.items()}
print(reversed)  # {1: 'a', 2: 'b', 3: 'c'}

 

43、將布林值轉換為數字

print(int(False))  # 0
print(float(True))  # 1.0

 

44、在算術運算中使用布林值

x = 10
y = 12
result = (x - False)/(y * True)
print(result)  # 0.833333333333333

 

45、將任何資料型別轉換為布林值

print(bool(.0))  # False
print(bool(3))  # True
print(bool("-"))  # True
print(bool("string"))  # True
print(bool(" "))  # True

 

46、將值轉換為復數

print(complex(10, 2))  # (10+2j)

 


也可以將數字轉換為十六進制數,

print(hex(11))  # 0xb

 

47、在串列的第一個位置添加一個值

如果使用append(),將從串列的最后一個位置插入新值,可以通過使用insert(),來指定插入新元素的索引和數值,那么串列的第一個位置為0,即下標為0,

my_list = [3, 4, 5]
my_list.append(6)
my_list.insert(0, 2)
print(my_list)  # [2, 3, 4, 5, 6]

 

48、Lambda函式只能在一行代碼中

無法通過多行代碼,來使用lambda函式,

comparison = lambda x: if x > 3:
                    print("x > 3")
                else:
                    print("x is not greater than 3")

 

報錯

 

 

 

49、Lambda中的條件陳述句應始終包含else陳述句

comparison = lambda x: "x > 3" if x > 3

 

運行上面的代碼,報錯,

 

 

 

這是由于條件運算式的特性,而不是lambda的導致的,

50、使用filter(),獲得一個新物件

my_list = [1, 2, 3, 4]

odd = filter(lambda x: x % 2 == 1, my_list)

print(list(odd))   # [1, 3]
print(my_list)  # [1, 2, 3, 4]

 

51、map()回傳一個新物件

map()函式將給定函式應用于可迭代物件(串列、元組等),然后回傳結果(map物件),

my_list = [1, 2, 3, 4]

squared = map(lambda x: x ** 2, my_list)

print(list(squared))   # [1, 4, 9, 16]
print(my_list)  # [1, 2, 3, 4]

 

52、range()的step引數

for number in range(1, 10, 3):
    print(number, end=" ")
# 1 4 7

 

53、range()默認從0開始

def range_with_zero(number):
    for i in range(0, number):
        print(i, end=' ')

def range_with_no_zero(number):
    for i in range(number):
        print(i, end=' ')

range_with_zero(3)  # 0 1 2
range_with_no_zero(3)  # 0 1 2

 

54、不需要和0比較長度

如果長度大于0,則默認為True,

def get_element_with_comparison(my_list):
    if len(my_list) > 0:
        return my_list[0]

def get_first_element(my_list):
    if len(my_list):
        return my_list[0]


elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)

print(first_result == second_result)  # True

 

55、可以在同一個作用域內多次定義一個方法
但是,只有最后一個會被呼叫,覆寫以前,

def get_address():
    return "First address"

def get_address():
    return "Second address"

def get_address():
    return "Third address"

print(get_address())  # Third address

 

56、在外部直接訪問私有屬性
在定義屬性或方法時,在屬性名或者方法名前增加兩個下劃線,定義的就是私有屬性或方法.如果想要在外部訪問,那么只需要在名稱前面加上 ‘_類名’ 變成 ‘_類名__名稱’,

class Engineer:
    def __init__(self, name):
        self.name = name
        self.__starting_salary = 62000


dain = Engineer('Dain')
print(dain._Engineer__starting_salary)  # 62000

 

57、檢查物件的記憶體使用情況

import sys
print(sys.getsizeof("bitcoin"))  # 56

 

58、定義一個方法,可以呼叫任意個引數

def get_sum(*arguments):
    result = 0
    for i in arguments:
        result += i
    return result

print(get_sum(1, 2, 3))  # 6
print(get_sum(1, 2, 3, 4, 5))  # 15
print(get_sum(1, 2, 3, 4, 5, 6, 7))  # 28

 

59、使用super()或父類的名稱呼叫父類的初始化
使用super函式呼叫父類的初始化方法,

class Parent:
    def __init__(self, city, address):
        self.city = city
        self.address = address


class Child(Parent):
    def __init__(self, city, address, university):
        super().__init__(city, address)
        self.university = university


child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university)  # Tsinghua University

 

使用父類的名稱呼叫父類

class Parent:
    def __init__(self, city, address):
        self.city = city
        self.address = address


class Child(Parent):
    def __init__(self, city, address, university):
        Parent.__init__(self, city, address)
        self.university = university


child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university)  # Tsinghua University

 

60、在類中使用 + 運算子
在兩個int資料型別之間使用 + 運算子時,將得到它們的和,而在兩個字串資料型別之間使用它時,會將其合并

print(10 + 1)  # 兩數相加
print('first' + 'second')  # 字串相加

 

這個就是運算子多載,你還可以在類中使用(add),

class Expenses:
    def __init__(self, rent, groceries):
        self.rent = rent
        self.groceries = groceries

    def __add__(self, other):
        return Expenses(self.rent + other.rent,
                        self.groceries + other.groceries)

april_expenses = Expenses(1000, 200)
may_expenses = Expenses(1000, 300)
total_expenses = april_expenses + may_expenses
print(total_expenses.rent)  # 2000
print(total_expenses.groceries)  # 500

 

61、在類中使用 < 和 == 運算子
下面定義一個操作多載示例( < 運算子),使用__lt__方法,

class Game:
    def __init__(self, score):
        self.score = score

    def __lt__(self, other):
        return self.score < other.score

first = Game(1)
second = Game(2)
print(first < second)  # True

 

同樣的,== 運算子使用__eq__方法

class Journey:
    def __init__(self, location, destination, duration):
        self.location = location
        self.destination = destination
        self.duration = duration

    def __eq__(self, other):
        return ((self.location == other.location) and
                (self.destination == other.destination) and
                (self.duration == other.duration))

first = Journey('Location A', 'Destination A', '30min')
second = Journey('Location B', 'Destination B', '30min')
print(first == second)

 

還有一些其他的定義

__sub__() for -
__mul__() for *
__truediv__() for /
__ne__() for !=
__ge__() for >=
__gt__() for >

 

62、為類的物件定義自定義的可列印版本

class Rectangle:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return repr('Rectangle with area=' + str(self.a * self.b))


print(Rectangle(3, 4))  # 'Rectangle with area=12'

 

63、交換字串中字符的大小寫

string = "This is just a sentence."
result = string.swapcase()
print(result)  # tHIS IS JUST A SENTENCE.

 

64、檢查字串是否都是空格

string = "  "
result = string.isspace()
print(result)  # True

 

65、檢查字串是否都是字母或數字

name = "Password"
print(name.isalnum())  # True
name = "Secure Password "
print(name.isalnum())  # False
name = "S3cur3P4ssw0rd"
print(name.isalnum())  # True
name = "133"
print(name.isalnum())  # True

 

66、檢查字串是否都是字母

string = "Name"
print(string.isalpha())  # True

string = "Firstname Lastname"
print(string.isalpha())  # False

string = "P4ssw0rd"
print(string.isalpha())  # False

 

67、根據引數洗掉字符

從右側開始

string = "This is a sentence with       "
print(string.rstrip())  # "This is a sentence with"

string = "this here is a sentence…..,,,,aaaaasd"
print(string.rstrip(".,dsa"))  # "this here is a sentence"

 

同樣的,左側也能操作,

string = "ffffffffFirst"
print(string.lstrip("f"))  # First

 

68、檢查字串是否為數字

string = "seven"
print(string.isdigit())  # False

string = "1337"
print(string.isdigit())  # True

string = "5a"
print(string.isdigit())  # False

string = "2**5"
print(string.isdigit())  # False

 

69、檢查字串是否為中文數字

# 42673
string = "四二六七三"

print(string.isdigit())  # False
print(string.isnumeric())  # True

 

70、檢查字串是否所有單詞都是大寫開頭

string = "This is a sentence"
print(string.istitle())  # False

string = "10 Python Tips"
print(string.istitle())  # True

string = "How to Print A String in Python"
# False
print(string.istitle())

string = "PYTHON"
print(string.istitle())  # False

 

71、在元組中使用負索引

numbers = (1, 2, 3, 4)

print(numbers[-1])  # 4
print(numbers[-4])  # 1

 

72、在元組中嵌套串列和元組

mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])

print(mixed_tuple[1])  # ['first', 'second', 'third']
print(mixed_tuple[0])  # ('aaaaaaaaaa', 3, 4)

 

73、快速統計元素在串列中出現的次數

names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"]

print(names.count("Besim"))  # 2

 

74、使用slice()獲取元素
使用slice()獲取最后n個元素,

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slicing = slice(-4, None)
print(my_list[slicing])  # [4, 5, 6]

print(my_list[-3])  # 4

 

使用slice()做切片任務,

string = "Data Science"
slice_object = slice(5, None)
print(string[slice_object])   # Science

 

75、計算元素在元組中出現的次數

my_tuple = ('a', 1, 'f', 'a', 5, 'a')

print(my_tuple.count('a'))  # 3

 

76、獲取元組中元素的索引

my_tuple = ('a', 1, 'f', 'a', 5, 'a')

print(my_tuple.index('f'))  #  2

 

77、步進獲得元組

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

print(my_tuple[::3])  # (1, 4, 7, 10)

 

78、通過索引獲取子元組

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

print(my_tuple[3:])  # (4, 5, 6, 7, 8, 9, 10)

 

79、將串列、集合、字典中所有元素洗掉

my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)  # []

my_set = {1, 2, 3}
my_set.clear()
print(my_set)  # set()

my_dict = {"a": 1, "b": 2}
my_dict.clear()
print(my_dict)  # {}

 

80、合并集合
使用union()方法,回傳一個新集合,

first_set = {4, 5, 6}
second_set = {1, 2, 3}

print(first_set.union(second_set))  # {1, 2, 3, 4, 5, 6}

 

還可以使用update()方法,將第二個集合的元素插入到第一個集合中去,

first_set = {4, 5, 6}
second_set = {1, 2, 3}
first_set.update(second_set)
print(first_set)  # {1, 2, 3, 4, 5, 6}

 

81、在函式里輸出結果

def is_positive(number):
    print("Positive" if number > 0 else "Negative")  # Positive

is_positive(-3)

 

82、if陳述句中的多個條件

math_points = 51
biology_points = 78
physics_points = 56
history_points = 72

my_conditions = [math_points > 50, biology_points > 50,
                 physics_points > 50, history_points > 50]

if all(my_conditions):
    print("Congratulations! You have passed all of the exams.")
else:
    print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.

 

83、在一個if陳述句中,至少滿足多個條件中的一個

math_points = 40
biology_points = 78
physics_points = 56
history_points = 72

my_conditions = [math_points > 50, biology_points > 50,
                 physics_points > 50, history_points > 50]

if any(my_conditions):
    print("Congratulations! You have passed all of the exams.")
else:
    print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.

 

84、任何非空字串都為True

print(bool("Non empty"))  # True
print(bool(""))  # False

 

85、任何非空串列、元組、字典都為True

print(bool([]))  # False
print(bool(set([])))  # False

print(bool({}))  # False
print(bool({"a": 1}))  # True

 

86、None、False、0都為False

print(bool(False))  # False
print(bool(None))  # False
print(bool(0))  # False

 

87、在函式中使用全域變數
函式無法直接修改全域變數的值

string = "string"

def do_nothing():
  string = "inside a method"


do_nothing()

print(string)  # string

 

可通過修飾符global,修改全域變數的值,

string = "string"

def do_nothing():
    global string
    string = "inside a method"

do_nothing()
print(string)  # inside a method

 

88、計算字串或串列中元素的數量
使用collections中的Counter計算字串或串列中元素的數量,

from collections import Counter
result = Counter("Banana")
print(result)  # Counter({'a': 3, 'n': 2, 'B': 1})

result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])
print(result)  # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

 

89、檢查2個字串是否為相同
可以使用Counter()方法,

from collections import Counter


def check_if_anagram(first_string, second_string):
    first_string = first_string.lower()
    second_string = second_string.lower()
    return Counter(first_string) == Counter(second_string)


print(check_if_anagram('testinG', 'Testing'))  # True
print(check_if_anagram('Here', 'Rehe'))  # True
print(check_if_anagram('Know', 'Now'))  # False

 

可以使用sorted()方法

def check_if_anagram(first_word, second_word):
    first_word = first_word.lower()
    second_word = second_word.lower()
    return sorted(first_word) == sorted(second_word)


print(check_if_anagram("testinG", "Testing"))  # True
print(check_if_anagram("Here", "Rehe"))  # True
print(check_if_anagram("Know", "Now"))  # False

 

90、使用itertools中的count計算元素的數量

from itertools import count

my_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

current_counter = count()

string = "This is just a sentence."

for i in string:
    if i in my_vowels:
        print(f"Current vowel: {i}")
        print(f"Number of vowels found so far: {next(current_counter)}")

 

輸出如下

Current vowel: i
Number of vowels found so far: 0
Current vowel: i
Number of vowels found so far: 1
Current vowel: u
Number of vowels found so far: 2
Current vowel: a
Number of vowels found so far: 3
Current vowel: e
Number of vowels found so far: 4
Current vowel: e
Number of vowels found so far: 5
Current vowel: e
Number of vowels found so far: 6

 

91、對字串或串列的元素進行次數排序

collections模塊的Counter(),默認情況下是不會根據元素的頻率對它們進行排序的,

from collections import Counter

result = Counter([1, 2, 3, 2, 2, 2, 2])
print(result)  # Counter({2: 5, 1: 1, 3: 1})
print(result.most_common())  # [(2, 5), (1, 1), (3, 1)]

 

map()函式將給定函式應用于可迭代物件(串列、元組等),然后回傳結果(map物件),

92、查找串列中出現頻率最高的元素

my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']

print(max(set(my_list), key=my_list.count))  # a

 

93、copy()和deepcopy()的區別

淺拷貝: 拷貝父物件,但是不會拷貝物件的內部的子物件,

深拷貝: 拷貝父物件. 以及其內部的子物件,

下面是一個copy()的例子,

first_list = [[1, 2, 3], ['a', 'b', 'c']]

second_list = first_list.copy()

first_list[0][2] = 831

print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 831], ['a', 'b', 'c']]

 

這里是一個deepcopy()的例子,

import copy

first_list = [[1, 2, 3], ['a', 'b', 'c']]

second_list = copy.deepcopy(first_list)

first_list[0][2] = 831

print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 3], ['a', 'b', 'c']]

 

94、訪問字典中不存在的鍵時,避免報錯
如果你想訪問字典一個不存在的鍵,代碼會報錯,

my_dictonary = {"name": "Name", "surname": "Surname"}
print(my_dictonary["age"])  

 

錯誤如下

KeyError: 'age'

 


可以通過使用defaultdict(),代碼將不會報錯,
from collections import defaultdict

my_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"

print(my_dictonary["age"])  

 

95、構建迭代器

class OddNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x = self.a
        self.a += 2
        return x


odd_numbers_object = OddNumbers()
iterator = iter(odd_numbers_object)

print(next(iterator))  # 1
print(next(iterator))  # 3
print(next(iterator))  # 5

 

96、洗掉串列的重復項

my_set = set([1, 2, 1, 2, 3, 4, 5])
print(list(my_set))  # [1, 2, 3, 4, 5]

 

97、列印模塊的安裝位置

import pandas

print(pandas)  # <module 'torch' from '/Users/...'

 

98、使用not in檢查一個值是否在串列中

odd_numbers = [1, 3, 5, 7, 9]
even_numbers = []

for i in range(9):
    if i not in odd_numbers:
        even_numbers.append(i)

print(even_numbers)  # [0, 2, 4, 6, 8]

 

99、sort()和sorted()的區別

sort():對原始串列進行排序

sorted():回傳一個新的排序串列

groceries = ['milk', 'bread', 'tea']

new_groceries = sorted(groceries)
# new_groceries = ['bread', 'milk', 'tea']

print(new_groceries)

# groceries = ['milk', 'bread', 'tea']
print(groceries)

groceries.sort()

# groceries = ['bread', 'milk', 'tea']
print(groceries)

 

100、使用uuid模塊生成唯一ID

UUID代表唯一識別符號

import uuid

# 根據主機ID、序列號和當前時間生成UUID
print(uuid.uuid1())  # 308490b6-afe4-11eb-95f7-0c4de9a0c5af

# 生成一個隨機UUID
# 資料原始碼自取君羊 872937351
print(uuid.uuid4())  # 93bc700b-253e-4081-a358-24b60591076a

 

 

最后

好了,今天的分享就到這里結束了,下次見~

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539694.html

標籤:其他

上一篇:OpenGPT搭建QQ機器人

下一篇:flask藍圖與專案一般結構

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more