我有一个二维数组:
[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
我该如何调用它的值?例如,我想要
print(name + " " + type)
并获得
霰弹枪 武器
我找不到方法去做到这一点。不知何故,print list[2][1]
没有输出任何内容,甚至没有错误。
我有一个二维数组:
[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print(name + " " + type)
并获得
霰弹枪 武器
我找不到方法去做到这一点。不知何故,print list[2][1]
没有输出任何内容,甚至没有错误。
通过索引访问适用于任何序列
(字符串、列表、元组)
:
>>> list1 = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
>>> list1[1]
['shotgun', 'weapon']
>>> print list1[1][1]
weapon
>>> print ' '.join(list1[1])
shotgun weapon
>>>
array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print " ".join(array[1])
使用[1]
对数组进行切片,然后使用' '.join()
连接数组的内容
In [80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
Out[80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
In [81]: a = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
In [82]: a[1]
Out[82]: ['shotgun', 'weapon']
In [83]: a[2][1]
Out[83]: 'weapon'
要获取所有列表元素,您应该使用以下for循环。
In [89]: a
Out[89]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
In [90]: for item in a:
print " ".join(item)
....:
shotgun weapon
pistol weapon
cheesecake food