【发布时间】: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 代码。 python的整个想法是可读性。如果您只需要晦涩的功能,请使用 Perl。
-
另见pythoncentral.io/how-to-slice-custom-objects-classes-in-python,您可以在自己的dict类型/子类中自定义
__getitem__。
标签: python dictionary ironpython slice