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

เขียนโปรแกรม Python กรองสมาชิกใน Series ที่ขึ้นต้นและลงท้ายด้วย 'a'


อินพุต - สมมติคุณมี Series

0    apple 1    oranges 2    alpha 3    aroma 4    beta

เอาต์พุต - ผลลัพธ์สมาชิกที่ขึ้นต้นและลงท้ายด้วย 'a'

2    alpha 3    aroma

วิธีที่ 1

  • สร้าง Series

  • สร้าง regular expression ตรวจสอบขึ้นต้นและลงท้ายด้วย 'a'

r'^[a]$|^([a]).*\1$'
  • สร้างลิสต์ว่าง วนลูปตรวจสอบ pattern เก็บค่าที่ตรง

for i in data:
    if(re.search(exp, i)):
        ls.append(i)
  • ตรวจสอบด้วย isin()

ตัวอย่าง

import pandas as pd
import re
l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)
exp = r'^[a]$|^([a]).*\1$'
ls = []
for i in data:
    if(re.search(exp, i)):
        ls.append(i)
print(data[data.isin(ls)])

ผลลัพธ์

2 alpha 3 aroma

วิธีที่ 2

ตัวอย่าง

import pandas as pd
import re
l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)
result = list(filter(lambda x:x.startswith('a') and x.endswith('a'),l))
print(data[data.isin(result)])

ผลลัพธ์

2 alpha 3 aroma