简体   繁体   中英

Index of an item within a list within a list?

Say that I have the following the code:

names_list = [['Abby', 'Albert'], ['Bert', 'Bob'], ['Gina', 'Greg']]

Now how would you print Albert ? To print 'abby', 'albert' I'd use:

print (names_list[0])

How would you use an item within the list though? Hope you understand what I mean.

print (names_list[0][1]) # prints Albert

To answer the question in your comment:

names_list = [['Abby', ['name', 'lastname']]]

print(names_list[0][1][1]) # prints lastname


              |            0               |  # names_list[0]
names_list = [['Abby', ['name', 'lastname']]]
               |  0  | |         1        |   # two elems within names_list[0]
                        | 0  |  |    1   |    # two elems in names_list[0][1]

You can do it in 2 steps

Python 3.3.1 (default, Sep 25 2013, 19:29:01) 
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> names_list = [['Abby', 'Albert'], ['Bert', 'Bob'], ['Gina', 'Greg']]
>>> 
>>> firstset = names_list[0]
>>> print (firstset)
['Abby', 'Albert']
>>> 
>>> albert = firstset[1]
>>> print (albert)
Albert

Or you can do it in one step

>>> print (names_list[0][1])
Albert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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