简体   繁体   English

Python - 从2d数组中获取值

[英]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, 记住几件事,

  1. don't name your list, list ... it's a python reserved word 不要列出你的名单, 列出 ......这是一个python保留字
  2. lists start at index 0. so mylist[0] would give [] 列表从索引0开始。所以mylist[0]会给[]
    similarly, mylist[1][0] would give 'shotgun' 同样, mylist[1][0]会给'shotgun'
  3. consider alternate data structures like dictionaries . 考虑像词典这样的备用数据结构。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM