Python - getting values from 2d arrays

我怕爱的太早我们不能终老 提交于 2020-01-14 14:10:04

问题


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,

  1. don't name your list, list... it's a python reserved word
  2. lists start at index 0. so mylist[0] would give []
    similarly, mylist[1][0] would give 'shotgun'
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!