Python - 从二维数组中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12826458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - getting values from 2d arrays
提问by Борис Цейтлин
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
我如何从中调用一个值?例如,我想print (name + " " + type)和GET
shotgun weapon
霰弹枪武器
I can't find a way to do so. Somehow print list[2][1]outputs nothing, not even errors.
我找不到这样做的方法。不知何故不print list[2][1]输出任何东西,甚至不输出错误。
采纳答案by sahhhm
>>> 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.
回答by Rohit Jain
Accessing through index works with any sequence(String, List, Tuple): -
通过索引访问适用于任何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 joinon the list, to get String out of list..
您可以在列表上使用join,从列表中获取字符串..
回答by kreativitea
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()
使用 切片到数组中[1],然后使用连接数组的内容' '.join()
回答by ronak
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.
要获取所有列表元素,您应该使用 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

