【问题标题】:check if item is in dictionary values [duplicate]检查项目是否在字典值中[重复]
【发布时间】:2020-07-20 00:00:58
【问题描述】:

我正在尝试为我的课堂编程编写游戏,我必须使用如下所示的字典:

board={
    'map': [{'x': 39,
        'y': 41}],
    'hubs': [{'x': 21,
            'y': 3,
            'structure_points': 1000,
            'capacity': 1500,
            'regen_rate': 25},
        {
            'x': 21,
            'y': 38,
            'structure_points': 1000,
            'capacity': 1500,
            'regen_rate': 25}],
    'peaks': [{'x': 10,
            'y': 10,
            'intensity': 200},
        {
            'x': 11,
            'y': 10,
            'intensity': 300},
        {
            'x': 12,
            'y': 10,
            'intensity': 400},
        {
            'x': 10,
            'y': 11,
            'intensity': 200},
        {
            'x': 10,
            'y': 12,
            'intensity': 500}],
    'cruisers': [{
        'alpha': {
            'health_points': 100,
            'available_energy': 400,
            'strike_cost': 10,
            'cruiser_deplacement': 10,
            'shooting_range': 1},
        'beta': {
            'health_points': 100,
            'available_energy': 400,
            'strike_cost': 10,
            'cruiser_deplacement': 10,
            'shooting_range': 1
        }}]}

基本上,该字典会创建一个棋盘并在其上放置不同的单位(山峰、枢纽和巡洋舰)。我想创建一个函数来检查某个位置是否已经有一个单元。我已经有这样的东西了:

def hub_exists(board, x_dest, y_dest):
    for hub in board.get('hubs', []):
        if hub.get('x') == x_dest and hub.get('y') == y_dest:
            return True
        else:
            return False

所以这个函数告诉我是否已经放置了一个集线器,但是如何让我的函数了解它是哪一个,以便我可以修改该集线器字典中的值?感谢您的帮助!

【问题讨论】:

  • 为什么不只返回 return hub 而不是返回布尔值?

标签: python python-3.x dictionary return


【解决方案1】:

你迭代字典列表的hub字典是当它的x和y匹配输入时要修改的字典,所以它可以简单地返回字典供调用者进行修改:

def get_hub(board, x_dest, y_dest):
    for hub in board.get('hubs', []):
        if hub.get('x') == x_dest and hub.get('y') == y_dest:
            return hub

...

hub = get_hub(board, 21, 3)
hub['capacity'] = 2000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多