You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python记忆游戏开发:嵌套列表在5×4网格中的正确应用

解决方案

核心思路

将用户输入的坐标(如a1、b2)拆解为列索引和行索引,再通过嵌套列表的索引规则获取对应符号:

  • 坐标首字符(a-e)对应列位置,转成0-4的索引(a=0,b=1,…,e=4)
  • 坐标第二个字符(1-4)对应行位置,转成0-3的索引(1=0,2=1,…,4=3)
  • 嵌套列表结构为grid[行索引][列索引],与你生成的create_grid返回结构完全匹配

实现代码

坐标转索引工具函数

def get_symbol_from_coordinate(grid, coordinate):
    # 拆分坐标字符,兼容大小写输入
    col_char = coordinate[0].lower()
    row_num = int(coordinate[1])
    
    # 字符转列索引:a→0,b→1...e→4
    col_index = ord(col_char) - ord('a')
    # 行号转行索引:1→0,2→1...4→3
    row_index = row_num - 1
    
    # 校验坐标合法性,避免越界
    if 0 <= col_index < 5 and 0 <= row_index < 4:
        return grid[row_index][col_index]
    else:
        raise ValueError("无效坐标,请输入a1-e4范围内的坐标")

完整使用示例

import random

cards = ["✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀",
         "✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀"]

def create_grid(cards):
    # 复制原列表再打乱,避免修改全局cards
    shuffled_cards = cards.copy()
    random.shuffle(shuffled_cards)
    return [shuffled_cards[i:i+5] for i in range(0, len(shuffled_cards), 5)]

# 生成游戏网格
game_grid = create_grid(cards)

# 测试坐标查询
try:
    user_input = input("请输入坐标(如a1):")
    target_symbol = get_symbol_from_coordinate(game_grid, user_input)
    print(f"坐标{user_input}对应的符号:{target_symbol}")
except ValueError as e:
    print(e)

关键细节说明

  • 高效索引转换:用ord()函数直接将字母转为ASCII码差值,无需额外字典映射,简洁高效
  • 输入容错:自动转换坐标首字符为小写,支持A1、B2等大写输入
  • 边界校验:加入索引范围检查,提前拦截无效坐标,避免程序崩溃
  • 原数据保护:在create_grid中复制原列表再打乱,确保全局cards可重复使用

内容的提问来源于stack exchange,提问作者qce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:55:19