71 trích đoạn code python cho các vấn đề hàng ngày

Tìm việc làm python lương cao

Các Vấn đề thường gặp

Trong phần này, chúng ta sẽ xem thử các kịch bản phổ biến khác nhau thường phát sinh và làm thế nào để giải quyết chúng với code Python. Đặc biệt, mình sẽ chia sẻ qua lời giải thích ngắn gọn về vấn đề với 1 danh sách các giải pháp với code Python. Sau đó, mình sẽ link tất cả các nguồn tài nguyên mà mình có. 

Đảo ngược Dictionary

# Use to invert dictionaries that have unique values
my_inverted_dict = dict(map(reversed, my_dict.items()))

# Use to invert dictionaries that have unique values
my_inverted_dict = {value: key for key, value in my_dict.items()}

# Use to invert dictionaries that have non-unique values
from collections import defaultdict
my_inverted_dict = defaultdict(list)
{my_inverted_dict[v].append(k) for k, v in my_dict.items()}

# Use to invert dictionaries that have non-unique values
my_inverted_dict = dict()
for key, value in my_dict.items(): 
  my_inverted_dict.setdefault(value, list()).append(key)

# Use to invert dictionaries that have lists of values
my_dict = {value: key for key in my_inverted_dict for value in my_map[key]}

Cộng các Element của 2 List

ethernet_devices = [1, [7], [2], [8374163], [84302738]]
usb_devices = [1, [7], [1], [2314567], [0]]

# The long way
all_devices = [
  ethernet_devices[0] + usb_devices[0], 
  ethernet_devices[1] + usb_devices[1], 
  ethernet_devices[2] + usb_devices[2], 
  ethernet_devices[3] + usb_devices[3], 
  ethernet_devices[4] + usb_devices[4]
]

# Some comprehension magic
all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)]

# Let's use maps
import operator 
all_devices = list(map(operator.add, ethernet_devices, usb_devices))

# We can't forget our favorite computation library
import numpy as np 
all_devices = np.add(ethernet_devices, usb_devices)

# Brute force with a try-except block (Python 3+)
try: 
  with open('/path/to/file', 'r') as fh: 
    pass
except FileNotFoundError: 
  pass

# Leverage the OS package (possible race condition)
import os 
exists = os.path.isfile('/path/to/file')

# Wrap the path in an object for enhanced functionality
from pathlib import Path
config = Path('/path/to/file') 
if config.is_file(): 
  pass

Chuyển đổi 2 List vào 1 Dictionary

column_names = ['id', 'color', 'style']
column_values = [1, 'red', 'bold']

# Convert two lists into a dictionary with zip and the dict constructor
name_to_value_dict = dict(zip(column_names, column_values))

# Convert two lists into a dictionary with a dictionary comprehension
name_to_value_dict = {key:value for key, value in zip(column_names, column_values)}

# Convert two lists into a dictionary with a loop
name_value_tuples = zip(column_names, column_values) 
name_to_value_dict = {} 
for key, value in name_value_tuples: 
  if key in name_to_value_dict: 
    pass # Insert logic for handling duplicate keys 
  else: 
    name_to_value_dict[key] = value

Kiểm tra Nếu 1 List đang Trống (Empty)

my_list = list()

# Check if a list is empty by its length
if len(my_list) == 0: 
  pass # the list is empty

# Check if a list is empty by direct comparison (only works for lists)
if my_list == []: 
  pass # the list is empty

# Check if a list is empty by its type flexibility **preferred method**
if not my_list: 
  pass # the list is empty

my_list = [27, 13, -11, 60, 39, 15]

# Clone a list by brute force
my_duplicate_list = [item for item in my_list]

# Clone a list with a slice
my_duplicate_list = my_list[:]

# Clone a list with the list constructor
my_duplicate_list = list(my_list) 

# Clone a list with the copy function (Python 3.3+)
my_duplicate_list = my_list.copy() # preferred method

# Clone a list with the copy package
import copy
my_duplicate_list = copy.copy(my_list)
my_deep_duplicate_list = copy.deepcopy(my_list)

# Clone a list with multiplication?
my_duplicate_list = my_list * 1 # do not do this

Khôi phục Mục sau cùng của 1 List

my_list = ['red', 'blue', 'green']

# Get the last item with brute force using len
last_item = my_list[len(my_list) - 1]

# Remove the last item from the list using pop
last_item = my_list.pop() 

# Get the last item using negative indices *preferred & quickest method*
last_item = my_list[-1]

# Get the last item using iterable unpacking
*_, last_item = my_list

Đầu tiên, chúng ta có thể tạo 1 lối tắt Windows với thiết lập như sau:

pathtotrc-image-titler.py -o pathtooutput

Bên cạnh, chúng ta cũng có thể tạo 1 file batch với đoạn code sau đây:

@echo off
pathtotrc-image-titler.py -o pathtooutput

Cuối cùng, chúng ta có thể tạo 1 script batch với code sau:

#!/bin/sh
python chúng tôi -o /path/to/output

Nếu bạn đang tìm giải thích chi tiết hơn, hãy xem thử bài “Cách tạo lối tắt tập lệnh Python với các đối số”.

Sắp xếp là 1 task thông thường mà bạn sẽ được mong đợi để biết cách triển khai thực hiện trong ngành Khoa học Máy tính. Cho dù việc sắp xếp các thuật toán trong hầu hết các chương trình giảng dạy cần sự tập trung cao độ, không ai sẽ nói cho bạn biết về độ phức tạp mà việc sắp xếp mang lại. Ví dụ: sắp xếp các con số khá đơn giản, vậy còn sắp xếp các string sẽ ra sao? Làm cách nào để ta quyết định 1 thứ tự thích hợp? Không sao cả, có khá nhiều sự lựa chọn trong Python:  

my_list = ["leaf", "cherry", "fish"]

# Brute force method using bubble sort
my_list = ["leaf", "cherry", "fish"]
size = len(my_list)
for i in range(size): 
  for j in range(size): 
    if my_list[i] < my_list[j]: 
       temp = my_list[i] 
       my_list[i] = my_list[j] 
       my_list[j] = temp

# Generic list sort *fastest*
my_list.sort()

# Casefold list sort
my_list.sort(key=str.casefold)

# Generic list sorted
my_list = sorted(my_list) 

my_list = sorted(my_list, key=str.casefold) 

# Custom list sort using current locale 
import locale
from functools import cmp_to_key
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) 

my_list = sorted(my_list, key=str.casefold, reverse=True)

1 trong những trường hợp sử dụng thú vị cho Python là vì ‘data science’. Nhưng không may, tuy nhiên, điều đó có nghĩa là bạn phải xử lý rất nhiều ‘raw data’ trong các định dạng khác nhau như file văn bản và bảng tính. May mắn rằng, Python có nhiều tiện ích được built-in cho việc đọc các định dạng file khác nhau. Ví dụ, chúng ta có thể phân tích 1 bảng tính 1 cách dễ dàng bằng cách:  

# Brute force solution
csv_mapping_list = []
with open("/path/to/data.csv") as my_data: 
  line_count = 0 
  for line in my_data: 
    row_list = [val.strip() for val in line.split(",")] 
    if line_count == 0: 
      header = row_list 
    else: 
      row_dict = {key: value for key, value in zip(header, row_list)}
      csv_mapping_list.append(row_dict) 
    line_count += 1

# CSV reader solution
import csv
csv_mapping_list = []
with open("/path/to/data.csv") as my_data: 
  csv_reader = csv.reader(my_data, delimiter=",") 
  line_count = 0 
  for line in csv_reader: 
    if line_count == 0: 
      header = line 
    else: 
      row_dict = {key: value for key, value in zip(header, line)} 
      csv_mapping_list.append(row_dict) 
    line_count += 1

# CSV DictReader solution
import csv
with open("/path/to/dict.csv") as my_data: 
  csv_mapping_list = list(csv.DictReader(my_data))

1 khi bạn đã có 1 list các dictionary, bạn có thể sẽ muốn tổ chức chúng trong vài trật tự cụ thể. Ví dụ: nếu các dictionary có 1 key cho date, ta có thể thử sắp xếp chúng theo thứ tự theo niên đại. May thay, sắp xếp là một nhiệm vụ tương đối nhẹ nhàng: 

csv_mapping_list = [
  { "Name": "Jeremy", "Age": 25, "Favorite Color": "Blue" }, 
  { "Name": "Ally", "Age": 41, "Favorite Color": "Magenta" }, 
  { "Name": "Jasmine", "Age": 29, "Favorite Color": "Aqua" }
]

# Custom sorting
size = len(csv_mapping_list)
for i in range(size): 
  min_index = i 
  for j in range(i + 1, size): 
      min_index = j 
      csv_mapping_list[i], csv_mapping_list[min_index] = csv_mapping_list[min_index], csv_mapping_list[i]

# List sorting function
csv_mapping_list.sort(key=lambda item: item.get("Age"))

# List sorting using itemgetter
from operator import itemgetter
f = itemgetter('Name')
csv_mapping_list.sort(key=f)

# Iterable sorted function
csv_mapping_list = sorted(csv_mapping_list, key=lambda item: item.get("Age"))

Các cách giải và nhiều chú thích hơn trong bài “Cách sắp xếp danh sách từ điển trong Python“.

# Define a generic 1D list of constants
my_list = [2, 5, -4, 6]

# Duplicate a 1D list of constants
[item for item in my_list]

# Duplicate and scale a 1D list of constants
[2 * item for item in my_list]

# Duplicate and filter out non-negatives from 1D list of constants
[item for item in my_list if item < 0]

# Duplicate, filter, and scale a 1D list of constants
[2 * item for item in my_list if item < 0]

# Generate all possible pairs from two lists
[(a, b) for a in (1, 3, 5) for b in (2, 4, 6)]

# Redefine list of contents to be 2D
my_list = [[1, 2], [3, 4]]

# Duplicate a 2D list
[[item for item in sub_list] for sub_list in my_list]

# Duplicate an n-dimensional list
def deep_copy(to_copy): 
  if type(to_copy) is list: 
    return [deep_copy(item) for item in to_copy] 
  else: 
    return to_copy

Gộp 2 Dictionary

yusuke_power = {"Yusuke Urameshi": "Spirit Gun"}
hiei_power = {"Hiei": "Jagan Eye"}
powers = dict()

# Brute force
for dictionary in (yusuke_power, hiei_power): 
  for key, value in dictionary.items(): 
    powers[key] = value

# Dictionary Comprehension
powers = {key: value for d in (yusuke_power, hiei_power) for key, value in d.items()}

# Copy and update
powers = yusuke_power.copy()
powers.update(hiei_power)

# Dictionary unpacking (Python 3.5+)
powers = {**yusuke_power, **hiei_power}

# Backwards compatible function for any number of dicts
def merge_dicts(*dicts: dict): 
  merged_dict = dict() 
  for dictionary in dicts: 
    merge_dict.update(dictionary) 
  return merged_dict

Định dạng 1 String

Dù thích hay không, chúng ta cũng sẽ tự thấy rằng mình mình hay vùi dập các lệnh print xuyên suốt dòng code cho mục đích debug nhanh hơn. Sau tất cả, 1 lệnh print được đặt đúng chỗ có thể giúp bạn tiết kiệm được khá nhiều thời gian. Tuy nhiên, không phải lúc này cũng dễ dàng và tiện lợi để hiển thị đúng thứ ta muốn. Nhưng không sao cả, Python có khá nhiều lựa chọn cho ‘format’: 

name = "Jeremy"
age = 25

# String formatting using concatenation
print("My name is " + name + ", and I am " + str(age) + " years old.")

# String formatting using multiple prints
print("My name is ", end="")
print(name, end="")
print(", and I am ", end="")
print(age, end="")
print(" years old.")

# String formatting using join
print(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))

# String formatting using modulus operator
print("My name is %s, and I am %d years old." % (name, age))

# String formatting using format function with ordered parameters
print("My name is {}, and I am {} years old".format(name, age))

# String formatting using format function with named parameters
print("My name is {n}, and I am {a} years old".format(a=age, n=name))

# String formatting using f-Strings (Python 3.6+)
print(f"My name is {name}, and I am {age} years old")

Hãy nghĩ rằng các giải pháp này không cần phải được dùng với lệnh print. Nói cách khác, bạn cứ thoải mái sử dụng các cách giải này như f-string bất kỳ đâu mà bạn cần.

# Python 2 only
print "Live PD",

# Backwards compatible (also fastest)
import sys
sys.stdout.write("Breaking Bad")

# Python 3 only
print("Mob Psycho 100", end="")

Kiểm tra Hiệu năng

Cuối cùng, bạn đôi lúc chỉ muốn so sánh 1 vài đoạn code. Và Python có vài sự lựa chọn đơn giản dành cho bạn: 

# Brute force solution
import datetime
start_time = datetime.datetime.now()
[(a, b) for a in (1, 3, 5) for b in (2, 4, 6)] 
# example snippet
end_time = datetime.datetime.now()
print end_time - start_time

# timeit solution
import timeit
min(timeit.repeat("[(a, b) for a in (1, 3, 5) for b in (2, 4, 6)]"))

# cProfile solutionimport cProfile
cProfile.run("[(a, b) for a in (1, 3, 5) for b in (2, 4, 6)]")

Cơ hội việc làm Software hấp dẫn tại TopDev đang chờ bạn!