python中2d,如何在Python中创建2D数组

Im trying to create an indexed 2D array within Python, but I keep running into errors, one way or another.

The following code:

#Declare Constants (no real constants in Python)

PLAYER = 0

ENEMY = 1

X = 0

Y = 1

AMMO = 2

CURRENT_STATE = 3

LAST_STATE = 4

#Initilise as list

information_state = [[]]

#Create 2D list structure

information_state.append([PLAYER,ENEMY])

information_state[PLAYER].append ([0,0,0,0,0])#X,Y,AMMO,CURRENT_STATE,LAST_STATE

information_state[ENEMY].append([0,0,0,0,0])#X,Y,AMMO,CURRENT_STATE,LAST_STATE

for index, item in enumerate(information_state):

print index, item

information_state[PLAYER][AMMO] = 5

Creates this output:

0 [[0, 0, 0, 0, 0]]

1 [0, 1, [0, 0, 0, 0, 0]]

IndexError: list assignment index out of range

Im used to using PHPs arrays, eg:

$array['player']['ammo'] = 5;

Is there anything similar in Python? I heard people recommending numpy, but i couldn't figure it out :(

Im new to this Python stuff.

Note: Using Python 2.7

解决方案

i think you should have a look at python's data structures tutorial and what you're looking for is called a dictionary here, which is a list of key-value pairs.

in your case, you could use a nested dictionary as a value for a key, so that you could call

## just examples for you ##

player_dict_info = {'x':0, 'y':0, 'ammo':0}

enemy_dict_info = {'x':0, 'y':0, 'ammo':0}

information_state = {'player': player_dict_info, 'enemy': enemy_dict_info}

and access every element like you did in php

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值