Reputation: 105
I have a 2d array:
[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
How do I call a value from it? For example I want to print (name + " " + type)
and get
shotgun weapon
I can't find a way to do so. Somehow print list[2][1]
outputs nothing, not even errors.
Upvotes: 3
Views: 33678
Reputation: 213223
Accessing through index works with any 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
>>>
You can use join on the list, to get String out of list..
Upvotes: 3
Reputation: 1778
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 getting all the list elements, you should use for loop as below.
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
Upvotes: 0
Reputation: 5365
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon
Remember a couple of things,
mylist[0]
would give []
mylist[1][0]
would give 'shotgun'
Upvotes: 6
Reputation: 1791
array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print " ".join(array[1])
slice into the array with the [1]
, then join the contents of the array using ' '.join()
Upvotes: 0