2012-10-07 92 views

回答

2

使用anyall取決於你是否要檢查是否人物的任何在字典中,或所有的人都是。這裏有您想要all,它假定一些示例代碼:

>>> s='abcd' 
>>> d={'a':1, 'b':2, 'c':3} 
>>> all(c in d for c in s) 
False 

另外,你可能希望得到一組在你的字符串,同時也是在你的字典鍵的字符:

>>> set(s) & d.keys() 
{'a', 'c', 'b'} 
0
string = "hello" 
dictionary = {1:"h", 2:"e", 3:"q"} 
for c in string: 
    if c in dictionary.values(): 
     print(c, "in dictionary.values!") 

如果你想檢查c是否在鍵中,使用dictionary.keys()來代替。

0
[char for char in your_string if char in your_dict.keys()] 

這將給你一個字符串中所有字符的列表,這些字符在字典中作爲鍵存在。

例如,

your_dict = {'o':1, 'd':2, 'x':3} 
your_string = 'dog' 
>>> [char for char in your_string if char in your_dict.keys()] 
['d', 'o'] 
相關問題