ske*_*rit 21 python dictionary list-comprehension list
我刚刚学习了列表理解,这是一种在单行代码中获取数据的快速方法.但有些事情让我烦恼.
在我的测试中,我在列表中有这样的词典:
[{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}]
Run Code Online (Sandbox Code Playgroud)
列表理解s = [ r for r in list if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ]完美地起作用(事实上,这是该行的结果)
无论如何,我意识到我并没有在我的其他项目中使用列表,我正在使用字典.像这样:
{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'}}
Run Code Online (Sandbox Code Playgroud)
这样我就可以简单地编辑我的字典了 var['test1420'] = ...
但是列表推导不起作用!我无法以这种方式编辑列表,因为您无法分配这样的索引.
还有另外一种方法吗?
ada*_*amk 36
你可以这样做:
s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])
Run Code Online (Sandbox Code Playgroud)
这需要你指定的字典并返回一个'过滤'字典.
如果dct是的话
{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}
Run Code Online (Sandbox Code Playgroud)
也许你正在寻找类似的东西:
[ subdct for key,subdct in dct.iteritems()
if 92<subdct['x']<95 and 70<subdct['y']<75 ]
Run Code Online (Sandbox Code Playgroud)
有点精确的是Python允许你链接不等式:
92<dct[key]['x']<95
Run Code Online (Sandbox Code Playgroud)
代替
if r['x'] > 92 and r['x'] < 95
Run Code Online (Sandbox Code Playgroud)
还要注意上面我已经写了一个列表理解,所以你得到一个列表(在这种情况下,是dicts).
在Python3中也有dict理解这样的东西:
{ n: n*n for n in range(5) } # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Run Code Online (Sandbox Code Playgroud)
在Python2中,等价物将是
dict( (n,n*n) for n in range(5) )
Run Code Online (Sandbox Code Playgroud)
我不确定你是否正在寻找一个dicts或dicts dict的列表,但是如果你理解上面的例子,很容易修改我的答案来得到你想要的.
听起来你想要这样的东西:
my_dict = {'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
'test277' : {'y': '072', 'x': '094', 'fname': 'test277'}}
new_dict = dict((k,v) for k,v in my_dict.items()
if 92 < int(v['x']) < 95 and 70 < int(v['y']) < 75)
Run Code Online (Sandbox Code Playgroud)
关于此代码的一些说明:
low < value < high 在 Python 3 中,您可以使用 dict 理解,这可能是一个更短的解决方案:
{key_expression(item) : value_expression(item) for item in something if condition}
Run Code Online (Sandbox Code Playgroud)
如果您想像原始问题一样过滤字典:
mydict = {'test1': {'y': 60},'test2': {'y': 70},'test3': {'y': 80}}
s = {k : r for k,r in mydict.items() if r['y'] < 75 }
> {'test1': {'y': 60}, 'test2': {'y': 70}}
Run Code Online (Sandbox Code Playgroud)
或者我们甚至可以在列表或范围之外创建一些东西。例如,如果我们想要一个包含所有奇数平方数的字典:
{i : i**2 for i in range(11) if i % 2 == 1}
> {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Run Code Online (Sandbox Code Playgroud)