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

Tìm chuỗi có độ dài lớn nhất trong Series Python

Mô tả bài toán

Cho một Series chứa các chuỗi: ["one", "two", "eleven", "pomegranates", "three"].

Yêu cầu: Tìm chuỗi có độ dài lớn nhất (trong trường hợp này là "pomegranates").

Giải pháp 1: Duyệt vòng lặp (cơ bản)

Khởi tạo biến lưu độ dài max và chuỗi tương ứng, duyệt qua từng phần tử để so sánh.

Ví dụ code

import pandas as pd

res = pd.Series(["one","two","eleven","pomegranates","three"])
maxlen = len(res[0])
maxstr = ""

for i in res:
    if len(i) > maxlen:
        maxlen = len(i)
        maxstr = i

print("Chuỗi dài nhất:", maxstr)
print("Độ dài:", maxlen)

Đầu ra

Chuỗi dài nhất: pomegranates
Độ dài: 12

Giải pháp 2: Sử dụng vector hóa pandas (khuyên dùng)

Pandas cung cấp phương thức str.len() và idxmax() để thực hiện nhanh gọn:

import pandas as pd

res = pd.Series(["one","two","eleven","pomegranates","three"])
# Cách 1: Dùng idxmax trên độ dài chuỗi
idx = res.str.len().idxmax()
print("Chuỗi dài nhất:", res[idx])

# Cách 2: Sắp xếp và lấy phần tử đầu
print("Chuỗi dài nhất:", res.loc[res.str.len().sort_values(ascending=False).index[0]])

Ưu điểm: Code ngắn gọn, hiệu năng tốt trên dữ liệu lớn nhờ vector hóa.