[英]Extract matching elements from 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",
},
]
我有一個已知的寬度和高度,所以我試圖創建一個包含與這些值匹配的項目的新數組。
所以我已知的寬度和高度是 150*25 所以我希望我的新數組看起來像這樣......
[
{
"dimensions" : {
"width" : 150,
"height" : 25,
"color" : 'blue',
},
"group": "starter",
},
]
我一直沒能找到一個可以遵循的例子,有人有嗎?
列表理解將起作用。 假設您在名為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))
輸出:
{'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.