Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เคล็ดลับและเทคนิค Python ที่จำเป็นสำหรับโปรแกรมเมอร์

ในบทความนี้จะครอบคลุมเคล็ดลับและเทคนิค Python ที่มีประโยชน์ ซึ่งจะเป็นประโยชน์เมื่อเขียนโปรแกรมในการแข่งขันเขียนโค้ดหรืองานของบริษัท เนื่องจากช่วยลดโค้ดและเพิ่มประสิทธิภาพการทำงาน

การสลับค่าตัวเลขสองตัวในที่เดียว (In-Place Swapping)

x, y = 50, 70
print(x, y)
# swapping
x, y = y, x
print(x, y)

ผลลัพธ์

50 70
70 50

สร้างสตริงเดียวจากลิสต์

lst = ['What', 'a', 'fine', 'morning']
print(" ".join(lst))

ผลลัพธ์

What a fine morning

ลบรายการซ้ำจากลิสต์

# Remove duplicates from a list
# วิธีนี้จะไม่รักษาลำดับ
lst = [2, 4, 4, 9, 13, 4, 2]
print("Original list:", lst)
new_lst = list(set(lst))
print(new_lst)

# วิธีนี้จะรักษาลำดับ
from collections import OrderedDict
lst = [2, 4, 4, 9, 13, 4, 2]
print(list(OrderedDict.fromkeys(lst).keys()))

ผลลัพธ์

Original list: [2, 4, 4, 9, 13, 4, 2]
[9, 2, 4, 13]
[2, 4, 9, 13]

กลับสตริง

# Reverse a string
s = "Hello, World!"
print(s[::-1])

letters = "abcdefghijklmnopqrstuvwxyz"
print(letters[::-1])

ผลลัพธ์

!dlroW ,olleH
zyxwvutsrqponmlkjihgfedcba

กลับลิสต์

# Reversing a list
lst = [20, 40, 60, 80]
print(lst[::-1])

ผลลัพธ์

[80, 60, 40, 20]

ทรานสโพสอาร์เรย์สองมิติ

# Transpose of a 2d array
matrix = [['a', 'b', 'c'], ['d', 'e', 'f']]
transMatrix = zip(*matrix)
print(list(transMatrix))

ผลลัพธ์

[('a', 'd'), ('b', 'e'), ('c', 'f')]

ตรวจสอบว่าสตริงสองตัวเป็น anagram หรือไม่

# Check if two strings are anagrams
from collections import Counter

def is_anagram(str1, str2):
    return Counter(str1) == Counter(str2)

print(is_anagram('hello', 'ollhe'))
print(is_anagram('Hello', 'hello'))

ผลลัพธ์

True
False

ตรวจสอบออบเจกต์ใน Python

# Inspect an object in python
lst = [1, 3, 4, 7, 9]
print(dir(lst))

ผลลัพธ์

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

นับลำดับลิสต์ (Enumerate)

# Enumerate a list
lst = [20, 10, 40, 50, 30, 40]
for i, value in enumerate(lst):
    print(i, ': ', value)

ผลลัพธ์

0 : 20
1 : 10
2 : 40
3 : 50
4 : 30
5 : 40

แฟกทอเรียลของตัวเลขใดๆ

# Factorial of any number
import functools
result = (lambda s: functools.reduce(int.__mul__, range(1, s+1), 1))(5)
print(result)

ผลลัพธ์

120

สร้างดิกชันนารีจากลำดับที่เกี่ยวข้องสองลำดับ

# Creating a dictionary from two related sequences
x1 = ('Name', 'EmpId', 'Sector')
y1 = ('Zack', 4005, 'Finance')
print(dict(zip(x1, y1)))

ผลลัพธ์

{'Name': 'Zack', 'EmpId': 4005, 'Sector': 'Finance'}