我有一个二维数组:
[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
如何从中调用值?例如,我想要print (name + " " + type)
并获得
霰弹枪武器
我找不到办法。不知怎的,print list[2][1]
没有输出任何内容,甚至没有输出错误。
答案 0 :(得分:6)
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon
记住几件事,
mylist[0]
会给[]
同样,mylist[1][0]
会给'shotgun'
答案 1 :(得分:3)
通过索引访问适用于任何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 ,将String从列表中删除..
答案 2 :(得分:0)
array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print " ".join(array[1])
使用[1]
切入数组,然后使用' '.join()
答案 3 :(得分:0)
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