【问题标题】:Slicing a dictionary by keys that start with a certain string按以某个字符串开头的键对字典进行切片
【发布时间】:2011-06-01 08:00:21
【问题描述】:

这很简单,但我喜欢一种漂亮的 Pythonic 方式。基本上,给定一个字典,返回仅包含以某个字符串开头的那些键的子字典。

» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby': 2, 'Baboon': 3}

用函数来做这件事相当简单:

def slice(sourcedict, string):
    newdict = {}
    for key in sourcedict.keys():
        if key.startswith(string):
            newdict[key] = sourcedict[key]
    return newdict

但肯定有更好、更聪明、更易读的解决方案吗?发电机可以在这里帮忙吗? (我从来没有足够的机会使用这些)。

【问题讨论】:

标签: python dictionary ironpython slice


【解决方案1】:

这个怎么样:

在 python 2.x 中:

def slicedict(d, s):
    return {k:v for k,v in d.iteritems() if k.startswith(s)}

在 python 3.x 中:

def slicedict(d, s):
    return {k:v for k,v in d.items() if k.startswith(s)}

【讨论】:

  • 不要隐藏slice 内置(即使几乎没有人使用它)。
  • 那个dict理解很好吃。而且我不知道slice 是内置的,wtf?
  • @Ignacio:当你在一个很小的本地函数中时,并不总是值得担心踩到内置函数——它们太多了,名字也太普通了。最好只为非平凡的函数(如果有的话)和全局函数担心它。毕竟内置函数不是关键字。
  • 没有字典理解方式dict((k, v) for k,v in d.iteritems() if k.startswith(s))
  • 2017 年:python 可以纯粹使用in:{k:d[k] for k in d if k.startswith(s)} 理解字典,不再需要调用函数。
【解决方案2】:

功能风格:

dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))

【讨论】:

  • 在 Python 中,函数式风格通常是你不想要的。
  • 嗯? dict-comprehension 方法当然属于我对“功能风格”的定义。
【解决方案3】:

Python 3 中使用 items() 代替:

def slicedict(d, s):
    return {k:v for k,v in d.items() if k.startswith(s)}

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 2014-12-02
    • 2012-07-13
    • 2014-05-23
    • 2021-11-20
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多