词典中的词典的Python列表理解?
我刚刚了解了列表的理解,这是一个很好的方法来获取一行代码中的数据。但是有一些东西让我失望。
I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me.
在我的测试中,我在列表中有这样的字典:
In my test I have this kind of dictionaries inside the list:
[{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}]
列表理解 s = [r for list in list if r ['x']> 92和r ['x'] 完美地工作(事实上,这行的结果)
The list comprehension s = [ r for r in list if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ]
works perfectly on that (it is, in fact, the result of this line)
无论如何,我意识到我不是真的在我的另一个项目中使用一个列表,我正在使用一个字典。像这样:
Anyway, I then realised I'm not really using a list in my other project, I'm using a dictionary. Like so:
{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'}}
这样我可以用 var ['test1420'] = ...
但列表推导不行!
我不能以这种方式编辑列表,因为您无法分配这样的索引。
But list comprehensions don't work on that! And I can't edit lists this way because you can't assign an index like that.
有另一种方法吗?
您可以这样做:
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 ])
这需要你指定的dict,并返回一个'过滤'dict。
This takes a dict as you specified and returns a 'filtered' dict.