Skip to main content
 首页 » 编程设计

python之比较两个字符串中是否存在元音的函数

2025年05月04日26sky-heaven

我编写了一个比较 2 个字符串的函数脚本,并判断它们是否具有相同的元音(种类和数字)。

例如:

sameVowels('aabcefiok','xcexvcxaioa') should return `true` 

和sameVowels('aabcefiok','xcexvcxaioia') 应该返回false

这是我基于列表的尝试。它不能很好地工作,我不确定为什么;在这个特定示例中,它为两者返回 true。

def sameVowels(s1, s2): 
L1=[] 
L2=[] 
L_vowles=['a','e','i', 'o','u','A','E','I','O', 'U'] #dont know how to use str.upper/lower on lists... 
 
for i in s1: 
    if i in L_vowles: 
        L1.append(i) 
for i in s2: 
    if i in L_vowles: 
        L2.append(i) 
 
 
for i in L1: 
    L1.count(i) 
 
for i in L2: 
    L2.count(i) 
 
return L1.count(i)== L2.count(i) 

如你所见,我创建了一些愚蠢的列表 - L_vowels...

我考虑过使用 sets 但我认为它不会有用,因为我不能将它用于任何类型的计数。

1.我的尝试有什么问题?

  1. 关于使用 dictionary 解决它有什么想法吗?

谢谢!

请您参考如下方法:

只需使用生成器表达式和排序:

def vowels(x): 
    return (i for i in x if i.lower() in "aeiou") 
 
def same_vowels(a, b): 
    return sorted(vowels(a)) == sorted(vowels(b))