首頁常見問題正文

Python實(shí)用小技巧匯總

更新時(shí)間:2023-03-17 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  Python編程在各行各業(yè)應(yīng)用都十分廣泛,對(duì)于初學(xué)者來說,掌握一些實(shí)用的Python小技巧十分關(guān)鍵,它們可以幫助我們?cè)趯?shí)際的工作中提高效率。接下來筆者列舉一些Python實(shí)用小技巧供各位參考:

    1.使用zip()函數(shù)來同時(shí)遍歷兩個(gè)或多個(gè)列表

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

  輸出:

Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

 2. 使用enumerate()函數(shù)來遍歷列表并返回元素的索引

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

  輸出:

Index 0: apple
Index 1: banana
Index 2: orange

 3. 使用列表推導(dǎo)式來創(chuàng)建列表

squares = [x**2 for x in range(1, 6)]

print(squares)

  輸出:

[1, 4, 9, 16, 25]

 4. 使用字典推導(dǎo)式來創(chuàng)建字典

fruits = ['apple', 'banana', 'orange']
prices = [0.5, 0.25, 0.75]

fruit_prices = {fruit: price for fruit, price in zip(fruits, prices)}

print(fruit_prices)

  輸出:

{'apple': 0.5, 'banana': 0.25, 'orange': 0.75}

 5. 使用set()函數(shù)來去重

numbers = [1, 2, 3, 2, 1, 4, 5, 4]

unique_numbers = set(numbers)

print(unique_numbers)

  輸出:

{1, 2, 3, 4, 5}

 

1679021725100_Python實(shí)用小技巧.jpg

  6. 使用in關(guān)鍵字來檢查元素是否在列表中

fruits = ['apple', 'banana', 'orange']

if 'apple' in fruits:
    print("I found an apple!")

  輸出:

I found an apple!

 7. 使用sorted()函數(shù)來對(duì)列表進(jìn)行排序

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

  輸出:

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

 8. 使用join()函數(shù)來連接字符串列表

fruits = ['apple', 'banana', 'orange']

fruit_string = ', '.join(fruits)

print(fruit_string)

  輸出:

apple, banana, orange

  希望這些小技巧能對(duì)大家有所幫助!

分享到:
在線咨詢 我要報(bào)名
和我們?cè)诰€交談!