Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Python-使用字典比较两个列表_List_Python 2.7_Dictionary - Fatal编程技术网

List Python-使用字典比较两个列表

List Python-使用字典比较两个列表,list,python-2.7,dictionary,List,Python 2.7,Dictionary,Python新手。我被要求编写一个函数sameVowels(s1,s2),给定两个字符串s1,s2,如果两个字符串的元音(种类和数字)完全相同,则返回True。 (想想如何使用字典……) 我试过这个: import string def sameVowels( s1 , s2 ) : d1 = {} d2 = {} vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ] for v1 in s1 : for k1 in vowels

Python新手。我被要求编写一个函数sameVowels(s1,s2),给定两个字符串s1,s2,如果两个字符串的元音(种类和数字)完全相同,则返回True。 (想想如何使用字典……)

我试过这个:

import string
def sameVowels( s1 , s2 ) :
   d1 = {}
   d2 = {}
   vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]

   for v1 in s1 :
      for k1 in vowels :
        if v1 == k1 :
            d1[k1] = v1

   for v2 in s2 :
      for k2 in vowels :
        if v2 == k2 :
            d2[k2] = v2
print d1
print d2
return d1 == d2

print sameVowels( 'aabcefiok' , 'xcexvcxaioa' )
print sameVowels( 'aabcefiok' , 'xcexvcxaioia' )
但我得到的是:

{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
True
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
True
最后一对应该为False,因为第二个字符串有一个额外的“i” 我真的不知道怎么做
请帮助:)

您可能希望存储像
{vouel:ocurrences}
这样的对,因此请尝试修改您的2
语句中的逻辑:

for v1 in s1 : # Iterate over string1
    if v1 in vowels: # Check if each letter is a vowel
        if v1 in d1: # If the vowel is in dict1
            d1[v1] += 1 # Add 1 to the actual value
        else: 
            d1[v1] = 1 # Add the vowel to dict1
对于
,第二个
也一样:

for v2 in s2 :
    if v2 in vowels:
        if v2 in d2:
            d2[v2] += 1
        else:
            d2[v2] = 1

一个稍微简单但性能较差的版本(因为我们正在计算每个字母):

另一种选择:

from collections import Counter
def sameVowels(s1,s2):
    vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
    filtered1 = filter(lambda x: x in vowels, s1)
    filtered2 = filter(lambda x: x in vowels, s2)
    f1 = Counter(filtered1)
    f2 = Counter(filtered2)
    return f1==f2

您正在导入但未使用
字符串
模块。去掉那个重要的东西;)我不明白这一行:因为字典是空的。.字母不在dict1中,你在字符串
s1
上循环,所以
v1
每次迭代都是一个字母。该行只检查字母
v1
是否为元音,技术上它检查
v1
是否为
元音列表的一个元素。这与词典无关。
from collections import Counter
def sameVowels(s1,s2):
    vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
    filtered1 = filter(lambda x: x in vowels, s1)
    filtered2 = filter(lambda x: x in vowels, s2)
    f1 = Counter(filtered1)
    f2 = Counter(filtered2)
    return f1==f2