【问题标题】:How to access List elements如何访问列表元素
【发布时间】:2012-05-23 16:42:56
【问题描述】:

我有一个清单

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

如何访问这个列表的每个元素?

【问题讨论】:

  • 这是一个非常基本的问题,让我相信您迫切需要阅读Python tutorial。例如,您的数据结构似乎没有多大意义,字典可能是更好的选择:cities = {"Vegas": "US", "London": "UK"}.
  • 另外,您将覆盖默认的list。查看here 并尽量不要重新定义默认数据结构(listsetdicttuple)或全局dir() 中不属于您的任何内容。跨度>

标签: python list


【解决方案1】:

我首先不称它为list,因为这是Python 内置list 类型的构造函数的名称。

但是一旦你将它重命名为 cities 或其他什么,你会这样做:

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])

【讨论】:

    【解决方案2】:

    很简单

    y = [['vegas','London'],['US','UK']]
    
    for x in y:
        for a in x:
            print(a)
    

    【讨论】:

      【解决方案3】:

      从 34 岁开始艰难地学习 Python

      试试这个

      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])
      

      【讨论】:

      • 我看不出这如何回答嵌套列表的问题。
      【解决方案4】:

      尝试list[:][0] 显示列表内每个列表的所有第一个成员不起作用。结果将与list[0][:] 相同。

      所以我像这样使用列表理解:

      print([i[0] for i in list])
      

      返回列表中每个列表的第一个元素值。

      PS:我使用变量list,因为它是问题中使用的名称。我不会使用它作为变量名,因为它是 Python 中的基本函数 list()

      【讨论】:

        【解决方案5】:

        打印列表中所有项目的递归解决方案:

        def printItems(l):
           for i in l:
              if isinstance(i,list):
                 printItems(i)
              else:
                 print i
        
        
        l = [['vegas','London'],['US','UK']]
        printItems(l)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-03
          • 1970-01-01
          • 2021-12-20
          • 1970-01-01
          • 2022-10-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多