Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lọc chuỗi bắt đầu và kết thúc bằng 'a' trong Series Python

Mô tả bài toán

Cho Series:

0    apple
1    oranges
2    alpha
3    aroma
4    beta

Yêu cầu: Lọc các chuỗi bắt đầu bằng 'a' VÀ kết thúc bằng 'a'. Kết quả: alpha, aroma.

Giải pháp 1: Regex với re.search

Biểu thức chính quy: r'^[a].*[a]$' (bắt đầu 'a', kết thúc 'a').

import pandas as pd
import re

l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)
exp = r'^[a].*[a]$'  # ^a...a$

ls = []
for i in data:
    if re.search(exp, i):
        ls.append(i)

result = data[data.isin(ls)]
print(result)

Giải pháp 2: Dùng startswith/endswith (khuyên dùng - dễ đọc hơn)

import pandas as pd

l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)

# Dùng filter + lambda
filtered = list(filter(lambda x: x.startswith('a') and x.endswith('a'), l))
result = data[data.isin(filtered)]
print(result)

# Hoặc vector hóa với str accessor (hiệu quả nhất)
mask = data.str.startswith('a') & data.str.endswith('a')
result = data[mask]
print(result)

Đầu ra

2    alpha
3    aroma
dtype: object

So sánh phương pháp

Phương phápĐộ phức tạpHiệu năngKhuyên dùng
Regex + vòng lặpTrung bìnhThấpKhi pattern phức tạp
startswith/endswith + filterDễ hiểuTrung bìnhCode rõ ràng
str accessor vector hóaĐơn giảnCaoKhuyên dùng nhất