[英]Extract matching elements from array
I have the following python3 array..我有以下 python3 数组..
[
{
"dimensions" : {
"width" : 50,
"height" : 75,
"color" : 'red',
},
"group": "starter",
},
{
"dimensions" : {
"width" : 150,
"height" : 25,
"color" : 'blue',
},
"group": "starter",
},
{
"dimensions" : {
"width" : 10,
"height" : 5,
"color" : 'yellow',
},
"group": "primary",
},
]
I have a known width and height so I am trying to create a new array that contains the item that matches these values.我有一个已知的宽度和高度,所以我试图创建一个包含与这些值匹配的项目的新数组。
So my known width and height is 150*25 so I want my new array to look like this...所以我已知的宽度和高度是 150*25 所以我希望我的新数组看起来像这样......
[
{
"dimensions" : {
"width" : 150,
"height" : 25,
"color" : 'blue',
},
"group": "starter",
},
]
I haven't been able to find an example to follow, does anybody have one?我一直没能找到一个可以遵循的例子,有人有吗?
A list comprehension will work.列表理解将起作用。 Assuming you have the data in a list called data
:假设您在名为data
的列表中有data
:
filtered_data = [item for item in data if item['dimensions']['width'] == 150
and item['dimensions']['height'] = 25]
data = [
{
"dimensions" : {
"width" : 50,
"height" : 75,
"color" : 'red',
},
"group": "starter",
},
{
"dimensions" : {
"width" : 150,
"height" : 25,
"color" : 'blue',
},
"group": "starter",
},
{
"dimensions" : {
"width" : 10,
"height" : 5,
"color" : 'yellow',
},
"group": "primary",
},
]
def search(x,y):
for item in data:
if x in item['dimensions'].values() and y in item['dimensions'].values():
return item
x = 150
y = 25
print (search(x,y))
output:输出:
{'dimensions': {'width': 150, 'height': 25, 'color': 'blue'}, 'group': 'starter'}
data = [
{
"dimensions" : {
"width": 50,
"height": 75,
"color": 'red',
},
"group": "starter",
},
# We want this one
{
"dimensions": {
"width": 150,
"height": 25,
"color": 'blue',
},
"group": "starter",
},
{
"dimensions": {
"width": 10,
"height": 5,
"color": 'yellow',
},
"group": "primary",
}
]
def find_match(data, height=0, width=0):
"""Return match based on height & width"""
for item in data:
if (item["dimensions"]["height"] == height) \
and (item["dimensions"]["width"] == width):
return item
return None
print('Found: {}'.format(find_match(data, 25, 150))) # Match found
print('Found: {}'.format(find_match(data, 100, 100))) # No match found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.