[英]Python - getting values from 2d arrays
I have a 2d array: 我有一个2d数组:
[[], ['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)
并得到
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]
什么都不输出,甚至没有输出错误。
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon
Remember a couple of things, 记住几件事,
mylist[0]
would give []
mylist[0]
会给[]
mylist[1][0]
would give 'shotgun'
mylist[1][0]
会给'shotgun'
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 join on the list, to get String out of list.. 您可以在列表中使用join ,以从列表中获取String ..
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()
连接数组的内容
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.