我正在嘗試撰寫一個函式,該函式通過一個np.array包含電子郵件的函式,我想以陣列的形式獲取電子郵件中存在的元音數量
我的嘗試是:
def number_of_vouls(email):
vouls = 'aeiouAEIOU'
name = [e.split('@')[0] for e in email]
return [sum(1 for c in name if c in vouls) for n in name]
number_of_vouls(np.array(['[email protected]', '[email protected]']))
output: [0, 0]
預期的輸出應該是:[5, 4]對于這種情況
我認為我的問題是我無法按內部字符回圈name但不知道如何解決它
uj5u.com熱心網友回復:
只需在 sum 函式中將 name 更改為 n
def number_of_vouls(email):
vouls = 'aeiouAEIOU'
name = [e.split('@')[0] for e in email]
return [sum(1 for c in n if c in vouls) for n in name]
number_of_vouls(np.array(['[email protected]', '[email protected]'])
uj5u.com熱心網友回復:
你可以這樣做:
emails = ["[email protected]","[email protected]"]
vowels = ["a","e","i","o","u"]
count = 0
result = []
for email in emails:
words = email.split("@")
for char in words[0]:
if char.lower() in vowels:
count =1
result.append(count)
print(result)
uj5u.com熱心網友回復:
另一種選擇可能是:
def number_of_vouls(email):
vouls = 'aeiouAEIOU'
name = [e.split('@')[0] for e in email]
return [len([a for a in n if vouls.find(a) != -1]) for n in name]
uj5u.com熱心網友回復:
有許多不同的方法可以做到這一點。這是另一種方法:
VOWELS = {*'aeiouAEIOU'}
def number_of_vowels(emails):
result = []
for email in emails:
localpart, *_ = email.split('@')
result.append(sum(map(lambda x: x in VOWELS, localpart)))
return result
print(number_of_vowels(['[email protected]', '[email protected]']))
uj5u.com熱心網友回復:
由于您使用的是 numpy 陣列,因此您可能需要查看vectorize函式:
number_of_vouls = np.vectorize(lambda x: sum([1 if y in "aeiou" else 0 for y in x.split("@")[0].lower()]))
print(number_of_vouls(np.array(['[email protected]', '[email protected]'])))
uj5u.com熱心網友回復:
使用小寫的vouls字符,然后用casefold方法計算它們。
import numpy as np
def number_of_vouls(email):
vouls = 'aeiou'
names = [e.split('@')[0] for e in email]
return [sum(name.casefold().count(v) for v in vouls) for name in names]
emails = np.array(['[email protected]', '[email protected]', '[email protected]'])
v = number_of_vouls(emails)
輸出
[4, 4, 3]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456071.html
上一篇:過濾記錄保留組中最近的記錄
