我有以下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",
},
]
我找不到一个可以效法的例子,有人吗?
答案 0 :(得分:1)
列表理解将起作用。假设数据在名为data
的列表中:
filtered_data = [item for item in data if item['dimensions']['width'] == 150
and item['dimensions']['height'] = 25]
答案 1 :(得分:1)
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'}
答案 2 :(得分:1)
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