Python-从2d数组中获取值

2024-05-29 02:39:56 发布

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

我有一个二维阵列:

[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]

如何从中调用值?例如,我想print (name + " " + type)

shotgun weapon

我找不到办法。不知何故print list[2][1]什么也不输出,甚至不输出错误。


Tags: namefoodtype错误listprintweapon办法
3条回答
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon

记住几件事

  1. 不要说出你的名单,list。。。这是一个python保留字
  2. 列表从索引0开始。所以mylist[0]会给出[]
    类似地,mylist[1][0]将给出'shotgun'
  3. 考虑像dictionaries这样的替代数据结构。
array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print " ".join(array[1])

使用[1]分割到数组中,然后使用' '.join()连接数组的内容

通过索引访问与任何sequence(String, List, Tuple)一起工作:

>>> list1 = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
>>> list1[1]
['shotgun', 'weapon']
>>> print list1[1][1]
weapon
>>> print ' '.join(list1[1])
shotgun weapon
>>>  

您可以在列表中使用join将字符串从列表中取出。。

相关问题 更多 >

    热门问题