How to access List elements

前端 未结 5 717
面向向阳花
面向向阳花 2020-11-27 19:30

I have a list

list = [[\'vegas\',\'London\'],[\'US\',\'UK\']]

How to access each element of this list?

相关标签:
5条回答
  • 2020-11-27 19:56

    I'd start by not calling it list, since that's the name of the constructor for Python's built in list type.

    But once you've renamed it to cities or something, you'd do:

    print(cities[0][0], cities[1][0])
    print(cities[0][1], cities[1][1])
    
    0 讨论(0)
  • 2020-11-27 20:03

    Recursive solution to print all items in a list:

    def printItems(l):
       for i in l:
          if isinstance(i,list):
             printItems(i)
          else:
             print i
    
    
    l = [['vegas','London'],['US','UK']]
    printItems(l)
    
    0 讨论(0)
  • 2020-11-27 20:06

    Learn python the hard way ex 34

    try this

    animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']
    
    # print "The first (1st) animal is at 0 and is a bear." 
    
    for i in range(len(animals)):
        print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])
    
    # "The animal at 0 is the 1st animal and is a bear."
    
    for i in range(len(animals)):
        print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])
    
    0 讨论(0)
  • 2020-11-27 20:08

    Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

    So i use list comprehension like this:

    [i[0] for i in list] which return first element value for each list inside list.

    0 讨论(0)
  • 2020-11-27 20:13

    It's simple

    y = [['vegas','London'],['US','UK']]
    
    for x in y:
        for a in x:
            print(a)
    
    0 讨论(0)
提交回复
热议问题