问题
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.
回答1:
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon
Remember a couple of things,
- don't name your list, list... it's a python reserved word
- lists start at index 0. so mylist[0]would give[]
 similarly,mylist[1][0]would give'shotgun'
- consider alternate data structures like dictionaries.
回答2:
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..
回答3:
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()
回答4:
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
来源:https://stackoverflow.com/questions/12826458/python-getting-values-from-2d-arrays