Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.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
使用python字典_Python_Dictionary - Fatal编程技术网

使用python字典

使用python字典,python,dictionary,Python,Dictionary,我正在写一个接受参数的函数。根据该参数,我想将其与字典的键集进行比较,并返回任何匹配项的键值。到目前为止,我只能返回与键匹配的参数 def func(str): a = [] b = {'a':'b','c':'d','e':'f'} for i in str: if i in b.keys(): a.append(i) return a 输出样本: func('abcdefghiabacdefghi') [a'、'c'、'e'、'a'、'c'、'e'] 想

我正在写一个接受参数的函数。根据该参数,我想将其与字典的键集进行比较,并返回任何匹配项的键值。到目前为止,我只能返回与键匹配的参数

def func(str):
  a = []
  b = {'a':'b','c':'d','e':'f'}
  for i in str:
    if i in b.keys():
      a.append(i)
  return a
输出样本:

func('abcdefghiabacdefghi')

[a'、'c'、'e'、'a'、'c'、'e']

想要的输出:


['b'、'd'、'f'、'b'、'd'、'f']

最好不要将
str
用作变量名。我认为你的函数可以写得像这样简单

def func(mystr):
  b = {'a':'b','c':'d','e':'f'}
  return [b[k] for k in mystr if k in b]
def func(mystr):
  a = []
  b = {'a':'b','c':'d','e':'f'}
  for i in mystr:
    if i in b:           # i in b works the same as i in b.keys()
      a.append(b[i])     # look up the key(i) in the dictionary(b) here
  return a
如果您不想使用列表理解,那么您可以这样修复它

def func(mystr):
  b = {'a':'b','c':'d','e':'f'}
  return [b[k] for k in mystr if k in b]
def func(mystr):
  a = []
  b = {'a':'b','c':'d','e':'f'}
  for i in mystr:
    if i in b:           # i in b works the same as i in b.keys()
      a.append(b[i])     # look up the key(i) in the dictionary(b) here
  return a

谢谢,但是在返回中使用值的引用在哪里?它很好用,我只是想理解。编辑:哦,我真傻,只要调用键它就会返回值。你可以使用键作为索引来获得值。这就是dicts的作用。嘿,卡尔,在编辑我的评论之前,我甚至都没看到你的评论。在我发布的示例函数中,我认为为了查找参数并返回键或值,我必须使用.values()或.keys()方法。谢谢你的回复。