从数组中提取匹配元素

2024-04-16 19:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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",
    },
]

我还没有找到一个可以效仿的榜样,有人有吗


Tags: 宽度高度groupbluered数组widthpython3
3条回答

一份清单就行了。假设您在名为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

相关问题 更多 >